如何使用nunit和moq进行异常处理?

cho*_*bo2 5 nunit nunit-2.5

我试图使用nunits新的异常处理方式,但我发现很难找到它的信息以及如何使用它与moq.

我现在有一个moq,它在一个模拟方法上抛出一个异常,但我不知道如何使用nunit捕获它并查看它.

Mar*_*son 14

有几种不同的方法可以做到这一点; 我使用Assert.Throws.

var exception = Assert.Throws<YourTypeOfException>(()=> Action goes here);
Run Code Online (Sandbox Code Playgroud)

例如

var exception = Assert
                .Throws<ArgumentNullException>(()=> new ChimpPuncher(null));
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据需要进一步查询异常对象,例如

Assert.That(exception.Message, Text.Contains("paramname");
Run Code Online (Sandbox Code Playgroud)