Reputation: 21
I have some problems trying to do unit test with the Startup.cs file. I have no idea how to do it without integration test. There is any way to do it? I leave this part of code that I would like to have in my unit test. Im using xUnit
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
Upvotes: 2
Views: 5832
Reputation: 17648
You should isolate the functions you want to test.
For example, if you use special configurations like this pseudo code, you can test it by first splitting it up:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.AddFoo();
}
public void AddFoo(this IApplicationBuilder app)
{
//stuff happens here
//and you can test this.
}
Sometimes it can be hard because most of them are extension methods. But normally you can Verify
if a specific function is being called.
If you have a tool like .net Peek
you can actually see which non extension method is being called and verify that one.
If you are trying to "unit"-test the whole startup.cs
, that's going to be hard, since the actual configuration is in there.
If you really want to test the whole flow, you must provide settings to be able to cope with the test run. You can create a custom webbuilder and call it with an actual client, but it's going to take a couple of extra if/else statements and it wont be pretty. We use a startup.cs
which have some virtuals, so we can overload the tricky part and give it a custom implementation just for testing. To create such a setup, you can use this example:
private TestServer InitTestServer(HttpClient mockedHttpClient)
{
var builder = new WebHostBuilder()
.UseContentRoot(newBasePath)
.UseEnvironment("UnitTest")
.UseConfiguration(Configuration)
.UseStartup<Startup>()
.ConfigureTestServices((services) =>
{
services.AddSingleton<IHttpClientFactory>(new CustomHttpClientFactory(mockedHttpClient));
//some configuration override
});
return new TestServer(builder);
}
Upvotes: 2