【问题标题】:How to replace Assert.Fail() with FluentAssertions如何用 FluentAssertions 替换 Assert.Fail()
【发布时间】:2017-12-15 13:56:58
【问题描述】:

我们目前正在转换一些使用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");
}

【问题讨论】:

  • 请发布您遇到的问题的代码示例。单元测试是一门艺术。如果不知道“那些”是什么,我们就无法回答“我应该用什么来有效地替换那些......”。
  • 通常Assert.Fail 用于由于if(value == null) { Assert.Fail("should not be null");} 之类的问题而到达的代码路径,因此您如何转换它们完全取决于导致代码到达它们的环境。
  • 听起来您应该使用Assert.Throws 开始,而不是try/Assert.Fail/catch 方法。

标签: c# unit-testing assertions fluent-assertions


【解决方案1】:

重组测试以利用.ShouldThrow&lt;&gt; 断言扩展。

[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 以更好地了解如何使用该库。

【讨论】:

    【解决方案2】:

    按照此处的示例,他只是处理了 Assert.Fail - 并使用 action 和 .ShouldThrow http://www.continuousimprover.com/2011/07/why-i-created-fluent-assertions-in.html

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2022-01-17
      • 2014-12-17
      相关资源
      最近更新 更多