0

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

我可以实现 using 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();
}
4

2 回答 2

1

如果你使用更高级的单元测试框架,比如 NUnit。您可以执行以下操作:

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

// Assert
Assert.IsInstanceOf<ArgumentException>(result);
于 2016-06-28T13:10:54.177 回答
-1

我不知道任何内置方式,但是您可以将该方法包装在断言异常中

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));
于 2016-06-28T13:07:31.783 回答