我想要了解我在测试期间注入控制器的Context并修改内存中的数据"数据库上下文的版本。
所以控制器看起来像这样
[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);
}
}
我希望在客户端获取请求之前以某种方式获取上下文,并修改将从数据库上下文返回的数据。
我在GitHub中有测试project
答案 0 :(得分:1)
如果您定位.NET Core,则无法使用任何自动模拟框架。
您可以做的最好的事情是将所有方法都放在TestContext
虚拟中,然后在单元测试中扩展它。
public class IntegrationTestContext : TestContext
{
// override methods here
}
然后您可以使用
var context = new IntegrationTestContext();
services.AddInstance<TestContext>(context);
您还可以在IntegrationTestContext
中捕获所需的任何额外信息,并从测试中访问它。