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

3
我正在尝试为MSTest项目配置EntityFramework以进行集成测试,通常我会通过启动项来配置我的项目,如下所示:
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项目相同的依赖注入,并以类似的方式配置我的测试。

1个回答

2
通常你应该有一个包含MyWebApp.StartupMyWebApp.appsettings.jsonMyWebApp,启动类会配置所有内容(它可能使用json配置文件)。
现在在MyWebApp.Test中(它应该引用MyWebApp),创建MyWebApp.Test.Startup,继承自MyWebApp.Startup,如果你需要覆盖某些东西,还要创建MyWebApp.Test.appsettings.json(例如使用不同的配置连接字符串),然后你可以像这样创建你的测试服务器:
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

1
有没有办法我可以只使用启动而不必拉入整个项目,理想情况下,我只想使用ServiceCollection来获取每个测试所需的内容。 - johnny 5
或者我应该创建一个新的Web API项目,设置我的服务集合,然后添加所需的NuGet包。 - johnny 5
@johnny5 启动类使用了项目中定义的其他类型,没有它们就无法工作。 - Cheng Chen
谢谢,我明白了,我要么得移动一堆包,要么引用该项目。 - johnny 5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接