C# 在测试项目中使用.Net核心依赖项注入
我正在尝试为MSTest项目中的集成测试配置EntityFramework,通常情况下,我可能会通过启动来配置我的项目,如下所示:C# 在测试项目中使用.Net核心依赖项注入,c#,.net-core,C#,.net Core,我正在尝试为MSTest项目中的集成测试配置EntityFramework,通常情况下,我可能会通过启动来配置我的项目,如下所示: public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); var defaultConnectionStrin
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
var defaultConnectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddEntityFrameworkSqlServer()
.AddDbContext<AstootContext>(options =>
options.UseSqlServer(defaultConnectionString))
.AddDbContext<PublicAstootContext>(options =>
options.UseSqlServer(defaultConnectionString));
//...
}
如何重用webapi项目使用的相同依赖项注入,从而以类似的方式配置测试 通常您应该有
MyWebApp
包含MyWebApp.Startup
和MyWebApp.appsettings.json
,Startup类配置所有内容(它可能使用json配置文件)
现在,在MyWebApp.Test
(应该参考MyWebApp
)中,创建从MyWebApp.Startup
继承的MyWebApp.Test.Startup
,如果您需要覆盖某些内容,以及MyWebApp.Test.appsettings.json
(使用不同的配置,例如ConnectionString),然后,您可以按如下方式创建测试服务器:
var builder = WebHost
.CreateDefaultBuilder()
.UseStartup<Startup>() //the Startup can be MyWebApp.Startup if you have nothing to customize
.ConfigureAppConfiguration(b => b.AddJsonFile("appsettings.json"));
var server = new TestServer(builder);
var client = server.CreateClient();
//send requests via client
var builder=WebHost
.CreateDefaultBuilder()
.UseStartup()//如果没有任何自定义项,则启动可以是MyWebApp.Startup
.ConfigureAppConfiguration(b=>b.AddJsonFile(“appsettings.json”);
var服务器=新的测试服务器(构建器);
var client=server.CreateClient();
//通过客户端发送请求
有一种方法,我可以直接使用启动,而不必拉动整个项目,理想情况下,我只想使用servicecollection获取每个测试所需的内容,还是应该创建一个新的WebAPI项目来设置我的服务集合,然后添加内容nugets@johnny5startup类使用项目中定义的其他类型,没有它们它无法工作。谢谢,我明白了,要么我必须移动,要么我必须移动一堆包,要么引用项目
var builder = WebHost
.CreateDefaultBuilder()
.UseStartup<Startup>() //the Startup can be MyWebApp.Startup if you have nothing to customize
.ConfigureAppConfiguration(b => b.AddJsonFile("appsettings.json"));
var server = new TestServer(builder);
var client = server.CreateClient();
//send requests via client