如何用FluentAssertions替换Assert.Fail() [英] How to replace Assert.Fail() with FluentAssertions

查看:188
本文介绍了如何用FluentAssertions替换Assert.Fail()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们当前正在转换一些使用Assert.IsTrue()Assert.AreEqual()Assert.IsNotNull()等的代码.C#的基本单元测试断言库

We are currently converting some code that was using Assert.IsTrue(), Assert.AreEqual(), Assert.IsNotNull(), etc. The basic unit test assert Library for C#

我们想使用FluentAssertions,例如value.Should().BeNull().

We want to use FluentAssertions, like value.Should().BeNull().

我在某些地方使用Assert.Fail()进行了一些测试.既然我们想取消每一个"Assert.*",而我在FluentAssertions中找不到等效的东西,那么我应该使用什么来有效地替换它们呢?

I'm stuck on a few tests using Assert.Fail() in some locations. What should I use to efficiently replace those, since we want to do away with every single "Assert.*", and I can't find an equivalent in 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<>断言扩展.

Restructure the test to utilize the .ShouldThrow<> assertion extension.

[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");
}

在上面的示例中,如果未引发预期的异常,则断言将失败,从而停止测试用例.

In the above example, if the expected exception is not thrown the the assertion would fail, stopping the test case.

您应该查看有关断言的文档,以更好地了解如何使用该库.

You should review the documentation on asserting exceptions to get a better understanding of how to use the library.

这篇关于如何用FluentAssertions替换Assert.Fail()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆