IT教程 ·

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

Java范型学习笔记

目次

为削减篇幅,隐蔽了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");
    }
}

能够看到,测试已经由过程

小cookie,大智慧

参与评论