在MSTest的单元测试中处理预期的异常

s.k*_*aul 3 c# unit-testing mstest exception

我正在DoingSomething()使用以下测试方法进行测试-

[TestMethod()]
[ExpectedException(typeof(ArgumentException),"Invalid currency.")]
public void ConvertCurrencyTest_ExhangeRate()
{
    try
    {
        DoingSomething();
    }
    catch (ArgumentException Ex)
    {
    }
    catch (Exception Ex)
    {
        Assert.Fail();
    }
}
Run Code Online (Sandbox Code Playgroud)

测试结果说DoingSomething()没有抛出异常。但这确实引发了异常。

我在这里想念什么?

Nko*_*osi 5

您在try / catch中使用了异常,因此不会冒起被测试捕获的异常。

卸下try/catch并让测试线束处理异常。任何其他异常自然会导致测试失败。

[TestMethod()]
[ExpectedException(typeof(ArgumentException),"Invalid currency.")]
public void ConvertCurrencyTest_ExhangeRate() {       
    DoingSomething();        
}
Run Code Online (Sandbox Code Playgroud)