I'm trying to configure EntityFramework for integration tests in an MSTest Project, normally I might configure my project through my startup like so:
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));
//...
}
My testing project looks like so:
[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()
{
}
}
How can I reuse the same dependency injection my webapi project uses and so configure my tests in a similar fashion.
Usually you should have MyWebApp
that contains MyWebApp.Startup
and MyWebApp.appsettings.json
, the startup class configures everything (it probably uses the json config file).
Now in MyWebApp.Test
(which should reference MyWebApp
), create MyWebApp.Test.Startup
that inherits from MyWebApp.Startup
if you need to override something, and MyWebApp.Test.appsettings.json
(to use different configs eg ConnectionString), then you can create your test server like this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.