ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# – 如何用FluentAssertions替换Assert.Fail()

2019-05-27 13:57:05  阅读:316  来源: 互联网

标签: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");
}

解决方法:

重构测试以利用.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以更好地了解如何使用该库.

标签:c,unit-testing,assertions,fluent-assertions
来源: https://codeday.me/bug/20190527/1163702.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有