Skip to content

Instantly share code, notes, and snippets.

@phillippelevidad
Created March 27, 2019 20:11
Show Gist options
  • Save phillippelevidad/770e53d56425a30790cea8c0c9c158c8 to your computer and use it in GitHub Desktop.
Save phillippelevidad/770e53d56425a30790cea8c0c9c158c8 to your computer and use it in GitHub Desktop.
xUnit: add Startup to test project and reuse configurations

xUnit: add Startup to test project and reuse configurations

Outline:

  • Create a xUnit test project;
  • Add the necessary NuGet packages:
    • Microsoft.AspNetCore.TestHost;
    • Microsoft.Extensions.Configuration.Json;
  • Add the Startup and InjectionFixture classes above;
  • Make your test classes implement IClassFixture<InjectionFixture> and receive an instance of InjectionFixture in their constructors;
  • Add the optional appsettings.json configuration file if you need it.

References:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using System;
using System.Net.Http;
namespace Tests
{
public class InjectionFixture : IDisposable
{
private readonly TestServer server;
private readonly HttpClient client;
public InjectionFixture()
{
server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
client = server.CreateClient();
}
public IServiceProvider ServiceProvider => server.Host.Services;
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
server.Dispose();
client.Dispose();
}
}
}
}
using Xunit;
namespace Tests
{
public class MyTests : IClassFixture<InjectionFixture>
{
private readonly InjectionFixture injection;
public MyTests(InjectionFixture injection)
{
this.injection = injection;
}
[Fact]
public void SomeTest()
{
// TODO: add test code.
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Tests
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// TODO: add your code.
}
public void Configure(IApplicationBuilder app)
{
// TODO: add your code.
}
}
}
@MdaslamArcadis
Copy link

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment