亲宝软件园·资讯

展开

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

江浙沪柯蓝 人气:2

目录

  • 定义一个待测试API
  • 测试用例

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

定义一个待测试API

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

[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
    private readonly SqliteDbContext _sqliteDbContext;
    public SampleController(SqliteDbContext sqliteDbContext)
    {
        _sqliteDbContext = sqliteDbContext;
    }
    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");
    }
}

可以看到,测试已通过

加载全部内容

相关教程
猜你喜欢
用户评论