Basic scenario - Xabaril/Acheve.TestHost GitHub Wiki
Startup
In the TestServer startup class you should include the authentication service and configure the .Net Core authentication handlers you want to use. In this case, the TestServer handler with its default scheme as the default scheme.
public class TestStartup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = TestServerDefaults.AuthenticationScheme;
})
.AddTestServer();
var mvcCoreBuilder = services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
ApiConfiguration.ConfigureCoreMvc(mvcCoreBuilder);
}
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
#Integration Tests
In your tests you can use an HttpClient with default credentials or build the request with the server RequestBuilder and the desired claims:
public class VauesWithDefaultUserTests : IDisposable
{
private readonly TestServer _server;
private readonly HttpClient _userHttpCient;
public VauesWithDefaultUserTests()
{
// Build the test server
var host = new WebHostBuilder()
.UseStartup<TestStartup>();
_server = new TestServer(host);
// You can create an HttpClient instance with a default identity
_userHttpCient = _server.CreateClient()
.WithDefaultIdentity(Identities.User);
}
[Fact]
public async Task WithHttpClientWithDefautIdentity()
{
var response = await _userHttpCient.GetAsync("api/values");
await response.IsSuccessStatusCodeOrThrow();
}
[Fact]
public async Task WithRequestBuilder()
{
// Or you can create a request and assign the identity to the RequestBuilder
var response = await _server.CreateRequest("api/values")
.WithIdentity(Identities.User)
.GetAsync();
await response.IsSuccessStatusCodeOrThrow();
}
public void Dispose()
{
_server.Dispose();
_userHttpCient.Dispose();
}
}
Both methods (WithDefaultIdentity and WithIdentity) accept an IEnumerabe<Claim> that should include the desired user claims for the request.
The extension method IsSuccessStatusCodeOrThrow
will validate that the status code in the response is a valid one (in the 2xx range) or it will read the content of the non valid response trying to add context to the failed test.
For this basic scenario the default TestServer schema is used and configured. It´s value is TestServer and is defined in the class TestServerDefaults.