C# testing — why does ExpectedException tagged met

2019-07-29 12:53发布

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

4条回答
做个烂人
2楼-- · 2019-07-29 13:19

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):

[TestMethod]
[ExpectedException(typeof(MyException))]
public void TestThrowsException() {

    Do.SomethingThatThrowsAnException();
    assert.fail("No exception ;-(");

}
查看更多
The star\"
3楼-- · 2019-07-29 13:23

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?

查看更多
神经病院院长
4楼-- · 2019-07-29 13:24

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.

查看更多
够拽才男人
5楼-- · 2019-07-29 13:43

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

查看更多
登录 后发表回答