通常您会测试某个方法是否抛出异常,如下所示。 我使用 FluentAssertions:
[Fact]
public void Exception_gets_thrown()
{
// Arrange
var foo = new Foo("validArgument");
// Act/Assert
foo.Invoking(f => f.Bar(null)) // null is an invalid argument
.ShouldThrow<ArgumentNullException>();
}
但是如果在构造函数中抛出异常,如何测试呢? 我就是这样做的,但是有没有更合适的方法 通过 FluentAssertions?
[Fact]
public void Constructor_throws_Exception()
{
// Arrange
Action a = () => new Foo(null); // null is an invalid argument
// Act/Assert
a.ShouldThrow<ArgumentNullException>();
}
最佳答案
这正是您应该如何测试异常,这就是 ShouldThrow<T>()
和 ShouldNotThrow<T>()
是为摆在首位而设计的。事实上,Invoking()
方法可能在下一个大版本 (2.0.0) 中被标记为过时。
关于c# - 有没有更合适的方法来测试构造函数是否抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10900373/