我想了解我在测试期间注入(inject) Controller 的上下文,并修改数据库上下文的“内存中”版本中的数据。
所以 Controller 看起来像这样
[Route("api/[controller]")]
public class TestController : Controller
{
private readonly TestContext _testContext;
public TestController(TestContext testContext)
{
_testContext = testContext;
}
[HttpGet]
public IActionResult Get()
{
return Ok(new { _testContext.Users });
}
}
测试看起来像这样
public class SiteTests
{
[Fact]
public async Task GetIt()
{
var server = TestServer.Create(app => { app.UseMvc(); }, services =>
{
services.AddMvc();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<TestContext>(options => options.UseInMemoryDatabase());
services.AddScoped<TestContext, TestContext>();
});
var client = server.CreateClient();
var response = await client.GetAsync("http://localhost/api/test");
var content = await response.Content.ReadAsStringAsync();
Assert.True(response.IsSuccessStatusCode);
}
}
我很想在客户端收到请求之前以某种方式获取上下文并修改将从数据库上下文返回的数据。
我有测试project在 GitHub 上
最佳答案
如果您的目标是 .NET Core,您将无法使用任何自动模拟框架。
您能做的最好的事情就是将 TestContext
中的所有方法虚拟化,然后在您的单元测试中扩展它。
public class IntegrationTestContext : TestContext
{
// override methods here
}
然后你可以使用
var context = new IntegrationTestContext();
services.AddInstance<TestContext>(context);
您还可以在 IntegrationTestContext
中捕获您想要的任何额外信息,并从您的测试中访问它。
关于在内存数据库中使用 Entity Framework 7 测试 ASP.NET 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34190361/