views:

851

answers:

3

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

+2  A: 

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...

Jon Skeet
Ditto throughout.
Marc Gravell
Congrats on the 60k, btw
Marc Gravell
Yes it is passing. To give you some context I am running this as a Silverlight 2 test, not sure if that matters. I get a green light in the test. To sanity check, if I change the code to this: [TestMethod] //[ExpectedException(typeof(MyException))] public void TestThrowsException() { throw new MyException(); }And this fails as expected (red light in silverlight test page).
Jason
I've just realised one potential cause for confusion - I've only used NUnit, not MS-Test. Which is this?
Jon Skeet
I am using Microsoft.VisualStudio,QualityTools.UnitTest.Silverlight, Microsoft.Silverlight.Testing and Microsoft.Silverlight.Testing.Framework. Basically I followed Jeff Wilcox's instructions at http://www.jeff.wilcox.name/2008/03/silverlight2-unit-testing/.
Jason
Hmm... don't know about that then. Sounds very odd :(
Jon Skeet
Jon you were right, I was confused about where I should be getting the testing framework from and when I figured that out and got the latest release things worked as expected. Thanks for your help.
Jason
Cool - I'm glad :)
Jon Skeet
A: 

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?

Peter Lillevold
I am using Microsoft.VisualStudio,QualityTools.UnitTest.Silverlight, Microsoft.Silverlight.Testing and Microsoft.Silverlight.Testing.Framework. Sorry, should have mentioned silverlight in the initial post.
Jason
A: 

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.

Jason