I have been struggling many hours with this issue. My WebAPI App works fine on local machine and production server but fails during an integration test of a controller that has dependency injection. Everything looks very clean and I have no idea why this is not working.
So here come the modules: The controller:
public SurveyController(IBoatInspectorRepository<Survey> repository)
{
_repository = repository;
}
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] {"value1", "value2"};
}
The start up:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>();
}
The test:
[Test]
public async Task GetSurveyDb_NullReturn_ReturnNotFound()
{
using (var testServer = CreateTestServer())
{
var client = testServer.CreateClient();
var value = await client.GetAsync("/api/survey/");
}
}
private TestServer CreateTestServer()
{
var builder = new WebHostBuilder()
.UseStartup<Startup>()
.ConfigureServices(services =>
services.AddScoped<IBoatInspectorRepository<Survey>, BoatInspectorRepository<Survey>>());
return new TestServer(builder);
}
If I debug this the debugger doesn't even go into the controller constructor. If I comment out the constructor and create an empty one everything works fine so it is 100% something to do with the dependency injection. Please help. Thank you.
UPDATE 1
So it seems that it is a problem with context initialization because if I do the following the constructor isn't initialized either.
public SurveyController(BoatInspectorContext context)
{
//debuger doesn't go inside here so must be something with context
}
So after two sleepless nights I found the fault... For some unovious reason the test server was not able to read the connection string to my db from apsettings.json using
so all I had to to was
For some reason this error wasn't coming up anywhere or maybe I didn't see it so after I spoted what it said it was pretty obvious.