3

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.

1 Answer 1

2

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 e.g. 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
Sign up to request clarification or add additional context in comments.

4 Comments

it’s there a way I can just use the start up without having to pull in the whole project, ideally I just want to use the servicecollection to grab out what I need for each test
Or should I just create a new web api project setup my services collection and then add maters nugets
@johnny5 The startup class uses other types defined in the project, it can't work without them.
Thanks, I see so either I have to move so I either have to move a bunch of packages, or reference the project

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.