I want to run a test server to host my main asp.net api application using AspNetCore.TestHost and run some tests using nUnit. So here are the parts:
Controller bit:
[Route("api/[controller]")]
public class SurveyController : Controller
{
[HttpGet("{surveyId}")]
public async Task<IActionResult> GetSurvey(int surveyId)
{
var entity = await _repository.GetEntity(surveyId);
if (entity==null)
return NotFound();
return Ok(entity);
}
}
I send surveyId = 0. If I check that in the browser or postman I get 404 Not Found - excellent. However, when I run the test, I get 200 Ok, and I return to the default route from the launch class, which looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.Run(async (context) =>
{
await context.Response.WriteAsync("MVC didn't find anything to route to!");
});
}
So, here are my test implications. Context
public class TestContext
{
private TestServer _server;
public HttpClient Client {
get;
private set;
}
public TestContext()
{
SetUpClient();
}
private void SetUpClient()
{
_server = new TestServer(new WebHostBuilder().UseStartup < Startup > ());
Client = _server.CreateClient();
}
}
Test
[Test]
public async Task GetSurveyDb_NullReturn_ReturnNotFound()
{
var response = await _sut.Client.GetAsync(":5000/api/survey/0");
var result = response.StatusCode;
var wtf= await response.Content.ReadAsStringAsync();
var expected = System.Net.HttpStatusCode.NotFound;
Assert.That(result, Is.EqualTo(expected));
}
: 5000/api/survey/0, , . : 5000, 500, http://localhost
, , . - ? .
1
, , . , .
private readonly IBoatInspectorRepository<Survey> _repository;
public SurveyController(IBoatInspectorRepository<Survey> repository)
{
_repository = repository;
}
:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>();
services.AddMvc();
services.AddEntityFrameworkNpgsql()
.AddDbContext<BoatInspectorContext>(
opt=>opt.UseNpgsql(Configuration.GetConnectionString("BoatInspectorConnectionString")));
}
, ... , , .
2
, . . :
private readonly IBoatInspectorRepository<Survey> _repository;
public SurveyController()
{
}
public SurveyController(IBoatInspectorRepository<Survey> repository)
{
_repository = repository;
}
, debug , , . , , 500 . , ... , , .