Just bumped into the same issue for a new test project and verified it works when using 2.2.0-preview2-35157 (released 12th of September)
(I am using NCrunch 3.20)
So, with net core 2.1 you can use:
Code:
//Use Microsoft.AspNetCore.TestHost (2.1.1) in test project. Test web app target framework netcoreapp2.1.
private HttpClient _client;
public MiscWebTest()
{ //constructor (non static for simplicity)
var builder = new WebHostBuilder()
.UseStartup<Startup>();
var testServer = new TestServer(builder);
_client = testServer.CreateClient();
}
[Test]
public void CanInvokeValues()
{
var response = _client.GetAsync("/api/values").Result;
response.EnsureSuccessStatusCode();
}
with net core 2.2 preview you can use:
Code:
//Web project: Microsoft.AspNetCore.App (2.2.0-preview2-35157), target framework netcoreapp2.2
//Test project: Microsoft.AspNetCore.Mvc.Testing (2.2.0-preview2-35157)
private HttpClient _client;
public MiscWebTest()
{ //constructor (non static for simplicity)
var webAppFactory = new WebApplicationFactory<Startup>();
_client = webAppFactory.CreateClient();
[Test]
public void CanInvokeValues()
{
var client = _testServer.CreateClient();
var response = client.GetAsync("/api/values").Result;
response.EnsureSuccessStatusCode();
}
*Edit: I bumped into another issue with above WebapplicationFactory for 2.2 when using Startup (deriving from the "production startup" type) defined in my test project. so i reverted back to the way I did it in 2.1
Quote:
System.NullReferenceException : Object reference not set to an instance of an object.
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateWebHostBuilder()
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer()
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient()
below did not help (which I use in netCore 2.1)
Code:
webAppFactoryDerivedStartup.WithWebHostBuilder(cfg =>
cfg.UseSetting(WebHostDefaults.ApplicationKey, typeof(Program).GetTypeInfo().Assembly.FullName));