C# testing — why does ExpectedException tagged method pass when exception not thrown?

回眸只為那壹抹淺笑 提交于 2019-12-24 10:56:14

问题


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


回答1:


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




回答2:


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.




回答3:


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:


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 ;-(");

}


来源:https://stackoverflow.com/questions/846056/c-sharp-testing-why-does-expectedexception-tagged-method-pass-when-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!