Skip to content

Let AspNetCore.Mvc.Testing stop the host before disposing it #29348

Closed

Description

@quixoticaxis

Is your feature request related to a problem? Please describe.

We're are trying to use Mvc.Testing to test web services that talk to each other using Apache Kafka. When the tests are run, a number of Kafka topics are created. After the tests complete, we delete the topics when disposing xunit's class fixture (the Dispose method of our custom application factory that derives from WebAppicationFactory<Startup> deletes the topics). The issue is that Mvc.Testing does not invoke the StopAsync on the host, and thus we leave Kafka consumers registered in the cluster, which, in turn, prevents the deletion of the topics.
Technically we could enforce consumers' closure when our services are disposed, but it won't do us any good as "consumers left not closed" are managed fine by the cluster itself.

The solution we have

There is a connected issue that was branded as a bug. Resolving a IHostApplicationLifetime at the test run was our first attempt to fix the issue. Unfortunately, it does not work.

For now we grab the host ourselves and call StopAsync on in:

var type = typeof(WebApplicationFactory<Startup>);
var field = type.GetField("_host", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var host = (IHost)field!.GetValue(this);
try
{
    Task.Run(async () => await host!.StopAsync(CancellationToken.None)).Wait();
}

but as you can see, it depends on the inner structure of WebApplicationFactory<T> and thus this solution is hard to maintain.

Describe the solution you'd like

MVC.Testing should either stop the host before disposing it or provide an option to stop the host before disposing it. It would make testing the services that handle some implicit state in their IHostedService.StopAsync calls easier.
The fact that MVC.Testing starts the host, but does not stop the host seems a bit strange.

Activity

  1. added
    area-mvc
    on Jan 15, 2021
  2. added
    bug
    on Jan 15, 2021
  3. added a commit that references this issue on Jan 20, 2021
    69e040e
  4. ghost locked as resolved and limited conversation to collaborators on Feb 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-mvcbug

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions