• .NET Core之单元测试(二):使用内存数据库处理单元测试中的数据库依赖



    为减少篇幅,隐藏了SampleEntity和SqliteDbContext

    定义一个待测试API

    如下,我们定义了一个名为Sample的API,其中有一个外部依赖项SqliteDbContext

    [Route("api/[controller]")]
    [ApiController]
    public class SampleController : ControllerBase
    {
        private readonly SqliteDbContext _sqliteDbContext;
        public SampleController(SqliteDbContext sqliteDbContext)
        {
            _sqliteDbContext = sqliteDbContext;
        }
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            var sampleData = await _sqliteDbContext.SampleEntity
                .SingleOrDefaultAsync(s => s.Id == id);
            return Ok(sampleData);
        }
    }
    

    测试用例

    本测试使用MSTest

    Install-Package Microsoft.EntityFrameworkCore.InMemory -Version 3.1.2

    private async Task<SqliteDbContext> GetSqliteDbContextAsync()
    {
        var options = new DbContextOptionsBuilder<SqliteDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
        var sqliteDbContext = new SqliteDbContext(options);
        sqliteDbContext.SampleEntity.Add(new Infrastructure.Entities.SampleEntity
        {
            Id = 1,
            BoolValue = false,
            DateTimeValue = DateTime.Now,
            StringValue = "sample"
        });
        await sqliteDbContext.SaveChangesAsync();
        return sqliteDbContext;
    }
    
    • 编写测试方法

    调用GetSqliteDbContextAsync()处理外部依赖项SqliteDbContext

    [TestClass]
    public class SampleControllerTest
    {
        [TestMethod]
        public async Task Get_ReturnOK_WithExpectedParameters()
        {
            // Arrange
            var dbContext = await GetSqliteDbContextAsync();
            var controller = new SampleController(dbContext);
    
            // Act
            var response = await controller.Get(1);
            var responseModel = ((OkObjectResult)response).Value as SampleEntity;
    
            // Assert
            Assert.IsInstanceOfType(response, typeof(OkObjectResult));
            Assert.IsTrue(responseModel.Id == 1);
            Assert.IsFalse(responseModel.BoolValue);
            Assert.IsTrue(responseModel.StringValue == "sample");
        }
    }
    

    可以看到,测试已通过
    在这里插入图片描述

  • 相关阅读:
    配置JAVA的环境变量
    Navicat Premium v12.0.23.0 安装,使用激活码激活
    mysql 5.7.33安装教程
    查看mysql服务
    postman测试post请求参数是List entity后端用@RequestBody接受lIst entity方式
    最简单的MySQL安装教程(数据库免安装版,免安装版,亲测好用) mysql-5.7.33-winx64.zip
    mysql数据库安装5.7.33
    java删除附件图片
    java生成条形码
    最高的牛
  • 原文地址:https://www.cnblogs.com/zhaobingwang/p/12345597.html
Copyright © 2020-2023  润新知