Skip to content

Instantly share code, notes, and snippets.

@johanvergeer
Last active May 21, 2019 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanvergeer/c45ae4766f939a4481031b465d8c8163 to your computer and use it in GitHub Desktop.
Save johanvergeer/c45ae4766f939a4481031b465d8c8163 to your computer and use it in GitHub Desktop.
An ASP.NET Core 2 Server test fixture for xUnit
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ApiTestsDbContext": "Server=(localdb)\\mssqllocaldb;Database=ApiTestDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("ApiTestsDbContext");
services.AddDbContext<PersonDbContext>(options =>
options.UseSqlServer(connectionString));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddScoped<IPersonRepository, PersonRepository>();
}
public class TestServerFixture : IDisposable
{
private readonly TestServer _testServer;
public HttpClient Client { get; set; }
public TestServerFixture()
{
var basePath = GetContentRootPath();
var builder = new WebHostBuilder()
.UseContentRoot(basePath)
.UseEnvironment("Development")
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("appsettings.json")
.Build())
.UseStartup<Startup>();
this._testServer = new TestServer(builder);
this.Client = this._testServer.CreateClient();
}
private string GetContentRootPath()
{
var testProjectPath = PlatformServices.Default.Application.ApplicationBasePath;
const string relativePathToWebProject = @"../../../../ImJohan.Blog.AspNetCoreApiTests";
return Path.Combine(testProjectPath, relativePathToWebProject);
}
public void Dispose()
{
this.Client.Dispose();
this._testServer.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment