Skip to content

ApiTests

ZhangYang edited this page Jul 18, 2019 · 1 revision

Using ASP.NET Core TestServer + EF Core In Memory DB Together

Integration tests ensure that an app's components function correctly at a level that includes the app's supporting infrastructure, such as the database, file system, and network. ASP.NET Core supports integration tests using a unit test framework with a test web host and an in-memory test server and EF core InMemory DB together.

Setup TestServer

To setup TestServer we use ApplicationBootstrap wiring components but with some InMemory components by ApplicationBootstrap.AddTestingServicesRegistrar. In here we register FakedEventStoreContextProvider and FakedEntityFramewokReadModelDbContextProvider

            ApplicationBootstrap.AddTestingServicesRegistrar(r =>
            {
                r.RegisterServices(register =>
                {
                    register.Register<IDbContextProvider<EventStoreContext>, FakedEventStoreContextProvider>();
                    register.Register<IDbContextProvider<RestAirlineReadModelContext>, FakedEntityFramewokReadModelDbContextProvider>();
                });
            });

            var hostBuilder = new WebHostBuilder()
                .UseEnvironment("UnitTest")
                .UseStartup<Startup>();

            _server = new TestServer(hostBuilder);
            HttpClient = _server.CreateClient();

Write API integration tests

Once we setup a TestServer, _apiTestClient.Get<RestAirlineHomeResource>("api/home"); will send a real request to TestServer and hit api/home resource, because it's a InMemory server so we can set a break point in the controller for debugging purpose by below test.

[Fact]
public async void ShouldGetHome()
{
    //Act
    var home = await _apiTestClient.Get<RestAirlineHomeResource>("api/home");

    //Assert
    home.ResourceLinks.Should().NotBeNull();
    home.ResourceLinks.Self.Should().NotBeNull();
    home.ResourceCommands.SelectJourneysCommand.Should().NotBeNull();
}
Clone this wiki locally