In the past I have tested for expected exceptions like this:
[TestMethod]
public void TestThrowsException() {
try {
Foo();
Assert.Fail();
} catch (MyException ex){//good
}
}
However I notice that there is a (cleaner?) way to test this using the ExpectedException attribute. Why does this test method pass when the exception is not thrown? Surely this defeats the purpose of the attribute.
[TestMethod]
[ExpectedException(typeof(MyException))]
public void TestThrowsException() {
}
[Edit] I am running this test using Silverlight 2
You should use 'ExpectedException' with an additional assert.fail, so that the test fails if the exception is not thrown (still in VS 2010 with .net 4 and Microsoft.VisualStudio.QualityTools.UnitTestFramework):
I've actually experienced that ReSharper 4.5 testrunner does not work with ExpectedException in NUnit 2.5. ...but this looks like MSTest ... can you elaborate on which test framework you are using and which test runner you are using to execute the tests?
Jon Skeet was in fact right, I did have an old version of the testing framework. I updated to the Dec 08 release here http://code.msdn.microsoft.com/silverlightut/Release/ProjectReleases.aspx?ReleaseId=1913 and got the expected behaviour when tagging with ExpectedException.
I've never seen that pass - is that really all you've got? Are you absolutely sure you have marked it as a
TestMethod
? Does the test runner show it passing? Have you definitely got the most recent code?I'll double check, but I'm sure that will fail...