Aspire tests and DI #7877
-
I'm working on a .Net 9 solution that uses Aspire, and the tests are setup with a fixture that seems fairly standard : public sealed class AspireTestFixture : IAsyncLifetime
{
public DistributedApplication App { get; private set; } = default!;
public HttpClient HttpClient { get; private set; } = default!;
public async Task InitializeAsync()
{
var builder = await DistributedApplicationTestingBuilder.CreateAsync<Projects.MyProject_AppHost>();
App = await builder.BuildAsync();
await App.StartAsync();
await App.Services
.GetRequiredService<ResourceNotificationService>()
.WaitForResourceAsync("api", KnownResourceStates.Running)
.WaitAsync(TimeSpan.FromSeconds(30));
HttpClient = new HttpClient { BaseAddress = App.GetEndpoint("api", "http") };
}
} This "api" project is a .Net backend that registers a PostgreSQL database connection using AddNpgsqlDbContext in its initialization phase. What I want (and cannot find a way how) : override/replace this database connection registration with a test version, specifically an in-memory database that doesn't require any Postgres/vendor specific initialization, without having to modify the API project itself. I don't want to add test code/dependencies in that project. Looking at the fixture, I don't see a way to do this, but maybe I'm missing something here ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
This is a really common question and it usually asked because of the experience users have writing asp.net core tests with web application factory. When you run integration tests currently with aspire it is black box testing, that is, we launch you entire system as separate processes and (much like what happens when you run) and you can poke at the state from the outside once the application is ready. You do not get access to the services of the projects, those run in a separate process to your test process. You can pass environment variables from the outside that influence these projects, but that’s about it. |
Beta Was this translation helpful? Give feedback.
Aspire’s testing capabilities are for black box testing your entire distributed application, not for writing unit tests or doing white box integration testing. If you want to run your single project in memory and stub out the database then continue to use web application factory.
If you want to use a real database and talk to your API to make sure data is persisted into the real Postgres database then aspire testing is the way to go.