我们目前正在转换一些使用Assert.IsTrue()
,Assert.AreEqual()
,Assert.IsNotNull()
等的代码。基本单元测试断言C#库
我们希望使用FluentAssertions,例如value.Should().BeNull().
我在某些地方使用Assert.Fail()
进行了一些测试。我应该用什么来有效地替换它们,因为我们想要消除每一个“断言。*”,我在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");
}
答案 0 :(得分:4)
重组测试以使用.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");
}
在上面的示例中,如果未抛出预期的异常,则断言将失败,从而停止测试用例。
您应该查看documentation on asserting exceptions以更好地了解如何使用该库。
答案 1 :(得分:2)
按照这里的例子,他只是处理了Assert.Fail - 并使用了动作和.ShouldThrow http://www.continuousimprover.com/2011/07/why-i-created-fluent-assertions-in.html