使用xUnit对单元测试异常消息进行测试

sdu*_*ooy 45 unit-testing mstest xunit

我目前正将我的MsTest单元测试转换为xUnit.使用xUnit,有没有办法测试异常消息?测试异常消息是否正确,而不仅仅是异常类型?

the*_*ric 72

我认为测试Exception类型和消息都是正确的.在xUnit中都很容易:

var exception = Assert.Throws<AuthenticationException>(() => DoSomething());
Assert.Equal(message, exception.Message);
Run Code Online (Sandbox Code Playgroud)

  • @CsabaToth你需要Assert.ThrowsAsync <>来做到这一点 (3认同)

use*_*319 7

最好使用 Record.Exception 方法,因为它匹配 AAA 模式:

    [Fact]
    public void Divide_TwoNumbers_ExpectException()
    {
        var sut = new Calculator();
        var exception = Record.Exception(() => sut.Divide(10, 0));
        Assert.IsType(typeof(DivideByZeroException), exception);
    }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 ...

  • xUnit2007:不要使用 typeof(System.DivideByZeroException) 表达式来检查类型。相反,您可以使用: Assert.IsType&lt;DivideByZeroException&gt;(exception) (2认同)