Warm tip: This article is reproduced from serverfault.com, please click

AspNetCore Integration Testing Multiple WebApplicationFactory Instances?

发布于 2019-03-01 11:58:03

Does any one know if it is possible to host multiple instances of WebApplicationFactory<TStartop>() in the same unit test?

I have tried and can't seem to get anywhere with this one issue.

i.e

_client = WebHost<Startup>.GetFactory().CreateClient();
var baseUri = PathString.FromUriComponent(_client.BaseAddress);
_url = baseUri.Value;

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Bearer", "Y2E890F4-E9AE-468D-8294-6164C59B099Y");

WebHost is just a helper class that allows me to build factory and then a client easily in one line.

Under the covers all it does is this:

new WebApplicationFactory<TStartup>() but a few other things too.

It would be nice if i could stand up another instace of a different web server to test server to server functionality.

Does anyone know if this is possible or not?

Questioner
IbrarMumtaz
Viewed
0
Chris Pratt 2019-03-01 22:35:40

No. It's not possible. WebApplicationFactory leans on xUnit's IClassFixture, which has to be applied at the class level, meaning you only get one bite at the apple. The WebApplicationFactory itself is capable of being customized per test, which fulfills most use cases where you're need a "different" one, but it doesn't help you wanting two totally separate active test servers at the same time.

However, that said, what you're wanting is a bad test design in the first place. The whole point of testing is to eliminate variables so you can actually ensure the piece of the SUT is actually working. Even in an integration testing environment, you're still just looking at one particular interaction between pieces of your application. Have two test servers, feeding off each other, effectively multiplies the variables giving you no assurance that either side is working correctly.