繁体   English   中英

在测试项目中使用.Net Core依赖注入

[英]Use .Net Core Dependency Injection with test project

我正在尝试配置EntityFramework以便在MSTest项目中进行集成测试,通常我可以像这样通过启动来配置项目:

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));
    //...
}

我的测试项目如下所示:

[TestClass]
public class UnitTest1 : ServiceTestBase
{
    string ConnectionString = @"Data Source=.\SQLEXPRESS;
                      AttachDbFilename=C:\source\Astoot\RestEzCore.Tests\TestDB\NORTHWND.MDF;
                      Integrated Security=True;
                      Connect Timeout=30;
                      User Instance=True";

    [TestInitialize]
    public void RegisterTestModules
    {

    }

    [TestMethod]
    public void TestMethod1()
    {
    }
}

如何重用我的webapi项目使用的相同依赖项注入,并以类似的方式配置测试。

通常你应该有MyWebApp包含MyWebApp.StartupMyWebApp.appsettings.json ,启动类配置的一切(它可能使用JSON配置文件)。

现在MyWebApp.Test (应参考MyWebApp ),创建MyWebApp.Test.Startup从继承MyWebApp.Startup如果你需要重写的东西,并MyWebApp.Test.appsettings.json (使用不同的configs如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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM