• .NET Core之单元测试(四):Fluent Assertions的使用


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

    测试通过
    在这里插入图片描述

  • 相关阅读:
    MySQL中redo日志
    MySQL中事务的分类
    MySQL中事务的概述ACID了解
    MySQL中UNSIGNED和ZEROFILL的介绍
    MySQL中死锁
    谈谈当前火热的“车联网”
    线性代数回顾:矩阵运算
    Spark作业调度阶段分析
    Spark——共享变量
    Spark编译与打包
  • 原文地址:https://www.cnblogs.com/zhaobingwang/p/12358573.html
Copyright © 2020-2023  润新知