Assert.Fail() を FluentAssertions に置き換える方法 質問する

Assert.Fail() を FluentAssertions に置き換える方法 質問する

現在、、、などを使用していた一部のコードを変換しています。C Assert.IsTrue()#の基本ユニットテストアサートライブラリAssert.AreEqual()Assert.IsNotNull()

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

ベストアンサー1

アサーション拡張を利用するためにテストを再構築します.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");
}

上記の例では、予期される例外がスローされない場合、アサーションは失敗し、テスト ケースが停止します。

確認すべきは例外のアサートに関するドキュメントライブラリの使用方法をより深く理解するため。

おすすめ記事