为减少篇幅,隐藏了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");
}
}
可以看到,测试已通过