Last active
May 21, 2019 19:39
-
-
Save johanvergeer/c45ae4766f939a4481031b465d8c8163 to your computer and use it in GitHub Desktop.
An ASP.NET Core 2 Server test fixture for xUnit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Logging": { | |
"LogLevel": { | |
"Default": "Warning" | |
} | |
}, | |
"AllowedHosts": "*", | |
"ConnectionStrings": { | |
"ApiTestsDbContext": "Server=(localdb)\\mssqllocaldb;Database=ApiTestDb;Trusted_Connection=True;MultipleActiveResultSets=true" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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