Search code examples
dotnet-aspire

Unit testing with aspire with containers


I might be being silly but can I use aspire like test containers > aka I want to spin up a container and run tests on it?

I have tried to use MS docs but it wants you to reference a c# project that I don't have.


Solution

  • Yes. But it has extra steps. You have probably already found these links or similar ones:

    https://learn.microsoft.com/en-us/dotnet/aspire/app-host/withdockerfile

    https://learn.microsoft.com/en-us/dotnet/aspire/testing/write-your-first-test?pivots=xunit

    1. Create an Aspire host project with the template setup

    2. Add whatever containers you want to the app setup in the Host project

    3. Create a test project

    4. Reference Aspire.Hosting.Testing and the host project you just made in your test project

    5. In the test project load the host project with the special command

      var appHost = await DistributedApplicationTestingBuilder .CreateAsync<Projects.{NAME OF YOUR HOST PROJECT WITH UNDERSCORES}>();

      The project reference will dynamically add the Host project name to the Projects class

    6. Build the appHost

    7. Get the resourceNotificationService for the resource/container you want to connect to

    8. Start the AppHost

    9. Wait for the resource to be ready via the notfication service

    10. Use the resourceNotificationService to get the ports that the container/resource is exposed on. these will be random ports. The Aspire Dashboard doesn't load, so you don't get the port you configured in the Host project

    11. Connect to the container and run your test.