ExpectedException attribute is not working
I have a really odd situation using Visual Studio unit testing framework. A test decorated as [TestMethod, ExpectedException(typeof(InvalidOperationException))]
fails with System.InvalidOperationException
.
If I remove all code from the test (to make sure it doesn't throw anything at all) - it passes. It is as if ExpectedException
is not even there...
If I start an empty project with a dummy test that does nothing but throwing InvalidOperationException
it totally works as expected.
Verified that neither ExpectedExceptionAttribute
nor InvalidOperationException
are overridden. Not sure what else to try here...
EDIT: Fixed the problem by removing reference to the Microsoft.VisualStudio.QualityTools.UnitTestFramework
v10.1 and adding v10.0. Not sure why would this matter or why other attributes worked just fine.
Personally I do not use the ExpectedExeption attribute because it does not allow you to specify exactly which statement is expected to throw the exception. For instance, there could be some problem in your test setup code that throws an InvalidOperationExeption which was not exected in your test and suddenly your test passes. Furthermore it does not allow you to inspect the Exeception, like Asserting it has the correct message.
I use the following approach
[TestMethod]
public void Test()
{
//Arrange
var sut = new ClassToTest();
sut.MethodThatShouldNotThrow();
//Act
try
{
sut.MethodToTestThatShuldThrow();
}
catch(InvalidOperationException ioex)
{
//Assert, here you could do additional Asserts on the Exception's properties
return;
}
Assert.Fail("Expected InvalidOperationException was not thrown");
}
链接地址: http://www.djcxy.com/p/12746.html