确保测试下的方法抛出了预期的异常,而不是设置测试用例的任何其他部分

本文关键字:设置 任何 其他部 测试用例 方法 测试 确保 异常 | 更新日期: 2023-09-27 17:52:16

我正在使用Visual Studio单元测试用例。我已经编写了单元测试用例,其中参数异常预计来自测试MethodUnderTest下的方法。假设测试用例的任何其他部分(设置部分)抛出预期的异常ArgumentException,那么我想强制我的测试用例应该失败。只有在设置正确且instance.MethodUnderTest();行代码抛出ArgumentException的情况下,它才应该通过。

我可以使用try catch实现,但我想知道是否有更好的方法来实现这一点。

[ExpectedException(typeof(ArgumentException))]
public void TestCaseMethod()
{        
    // Set up
    Mock<ITestClass> testM = new Mock<ITestClass>();
    AnimalClass instance = new AnimalClass(testM.Object);
    // call the method under test
    instance.MethodUnderTest();
}

确保测试下的方法抛出了预期的异常,而不是设置测试用例的任何其他部分

如果您使用更高级的单元测试框架,如NUnit。你可以这样做:

// Act
var result = Assert.Throws<Exception>(() => instance.MethodUnderTest));
// Assert
Assert.IsInstanceOf<ArgumentException>(result);

我不知道有什么内置的方法,但是你可以用assert异常来包装这个方法

private void AssertException<T>(Action method)
    where T : Exception
{
    try
    {
        method();
        Assert.Fail();
    }
    catch (T e)
    {
        Assert.IsTrue(true);
    }
}

然后调用

[TestMethod]
public void TestCaseMethod()
{        
    // Set up
    Mock<ITestClass> testM = new Mock<ITestClass>();
    AnimalClass instance = new AnimalClass(testM.Object);
    // call the method under test
    AssertException<ArgumentException>(instance.MethodUnderTest)
}

或者,如果方法接受参数或返回值

AssertException<MyException>(() => instance.ParameterisedFunction(a, b));