如何包含内部方法

时间:2010-08-12 11:22:46

标签: unit-testing nunit

我不想使用[ExpectedException(ExceptionType = typeof(Exception),ExpectedMessage =“”)]而是想在我的方法中包含异常。我能这样做吗?任何一个例子。

由于

3 个答案:

答案 0 :(得分: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);
   }
}

答案 1 :(得分:1)

你的问题没有多大意义。作为预感,我猜你在询问是否在单元测试中发现异常,然后即使异常被提出也可以执行断言?

[TestMethod]
public void Test1()
{
  try{
    // You're code to test.
  }
  catch(Exception ex){
   Assert.AreEqual(1, 1); // Or whatever you want to actually assert.
  }
}

编辑:

或者

[TestMethod]
public void Test1()
{
  try{
    // You're code to test.
    AreEqual(1, 1); // Or whatever you want to actually assert.
  }
  catch(Exception ex){
   Assert.Fail();
  }
}

答案 2 :(得分:0)

类似的东西:

[TestMethod]
public void FooTest()
{
  try
  {
    // run test
    Assert.Fail("Expected exception had not been thrown");
  }
  catch(Exception ex)
  {
    // assert exception or just leave blank
  }
}