.NET Core之單元測試(四):Fluent Assertions的使用

什麼是Fluent Assertions

Fluent Assertions.NET 平臺下的一組擴展方法,用於單元測試中的斷言。它使你的單元測試中的斷言看起來更天然流暢。斷言風格以下:github

string actual = "ABCDEFGHI";
actual.Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9);

更多內容可查看 Fluent Assertions Documentationsql

待測試API

[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
    var sampleData = await _sqliteDbContext.SampleEntity
        .SingleOrDefaultAsync(s => s.Id == id);

    if (sampleData?.StringValue == "ping")
    {
        var pingOk = _foo.Ping("localhost");
        if (!pingOk)
            return NotFound();
    }

    return Ok(sampleData);
}

測試用例

Install-Package FluentAssertions -Version 5.10.2api

咱們對前文中的測試用例進行修改,改動以下:async

// Assert
var result = response.Should().BeOfType<OkObjectResult>().Subject;
var sampleData = result.Value.Should().BeAssignableTo<SampleEntity>().Subject;
sampleData.Id.Should().Be(2);
sampleData.BoolValue.Should().BeFalse();
sampleData.StringValue.Should().Be("ping");

完整代碼以下單元測試

[TestMethod]
public async Task Get_ReturnOK_WithPingTrue_UsingFluentAssertions()
{
    // Arrange
    var dbContext = await GetSqliteDbContextAsync();

    var loggerMock = new Mock<ILogger<SampleController>>();
    var logger = loggerMock.Object;

    var fooMock = new Mock<IFoo>();
    fooMock.Setup(foo => foo.Ping("localhost")).Returns(true);
    var foo = fooMock.Object;

    var controller = new SampleController(dbContext, logger, foo);

    // Act
    var response = await controller.Get(2);

    // Assert
    var result = response.Should().BeOfType<OkObjectResult>().Subject;
    var sampleData = result.Value.Should().BeAssignableTo<SampleEntity>().Subject;
    sampleData.Id.Should().Be(2);
    sampleData.BoolValue.Should().BeFalse();
    sampleData.StringValue.Should().Be("ping");
}

測試經過
在這裏插入圖片描述測試

相關文章
相關標籤/搜索