Kai*_*Kid 7 c# unit-testing assertions fluent-assertions
目前,我们正在将使用一些代码Assert.IsTrue(),Assert.AreEqual(),Assert.IsNotNull(),等的基本单元测试断言库C#
我们要使用FluentAssertions,例如 value.Should().BeNull().
我Assert.Fail()在某些地方使用了一些测试。我想用什么来有效地替换那些,因为我们要删除每个“ Assert。*”,而我在FluentAssertions中找不到等效的东西?
这是一个例子
[TestMethod, TestCategory("ImportantTest")]
public void MethodToTest_Circumstances_ExpectedResult()
{
// Arrange
var variable1 = new Type1() { Value = "hello" };
var variable2 = new Type2() { Name = "Bob" };
// Act
try
{
MethodToTest(variable1, variable2);
// This method should have thrown an exception
Assert.Fail();
}
catch (Exception ex)
{
ex.Should().BeOfType<DataException>();
ex.Message.Should().Be(Constants.DataMessageForMethod);
}
// Assert
// test that variable1 was changed by the method
variable1.Should().NotBeNull();
variable1.Value.Should().Be("Hello!");
// test that variable2 is unchanged because the method threw an exception before changing it
variable2.Should().NotBeNull();
variable2.Name.Should().Be("Bob");
}
Run Code Online (Sandbox Code Playgroud)
重组测试以利用.ShouldThrow<>断言扩展。
[TestMethod, TestCategory("ImportantTest")]
public void MethodToTest_Circumstances_ExpectedResult() {
// Arrange
var variable1 = new Type1() { Value = "hello" };
var variable2 = new Type2() { Name = "Bob" };
// Act
Action act = () => MethodToTest(variable1, variable2);
// Assert
// This method should have thrown an exception
act.ShouldThrow<DataException>()
.WithMessage(Constants.DataMessageForMethod);
// test that variable1 was changed by the method
variable1.Should().NotBeNull();
variable1.Value.Should().Be("Hello!");
// test that variable2 is unchanged because the method threw an exception before changing it
variable2.Should().NotBeNull();
variable2.Name.Should().Be("Bob");
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,如果未引发预期的异常,则断言将失败,从而停止测试用例。