如何包含内部方法

lea*_*ing 1 nunit unit-testing

我不想使用[ExpectedException(ExceptionType = typeof(Exception),ExpectedMessage ="")]而是希望在我的方法中包含异常.我能这样做吗?请举个例子.

谢谢

Man*_*red 5

有时我想测试特定异常属性的值,在这种情况下,我有时会选择不使用ExpectedException属性.

相反,我使用以下方法(一个例子):

[Test]
public void MyTestMethod() {
   try {
      var obj = new MyClass();
      obj.Foo(-7); // Here I expect an exception to be thrown
      Assert.Fail(); // in case the exception has not been thrown
   }
   catch(MySpecialException ex) {
      // Exception was thrown, now I can assert things on it, e.g.
      Assert.AreEqual(-7, ex.IncorrectValue);
   }
}
Run Code Online (Sandbox Code Playgroud)