.NET Core之单元测试(四):Fluent Assertions的使用
江浙沪柯蓝 人气:1目录
- 什么是Fluent Assertions
- 待测试API
- 测试用例
什么是Fluent Assertions
Fluent Assertions 是 .NET 平台下的一组扩展方法,用于单元测试中的断言。它使你的单元测试中的断言看起来更自然流畅。断言风格如下:
string actual = "ABCDEFGHI";
actual.Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9);
更多内容可查看 Fluent Assertions Documentation
待测试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.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");
完整代码如下
[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");
}
测试通过
加载全部内容