In Startup I isolated ConfigureAppServices to a separate private method so I can override it in TestStartup in my Test project
public virtual void ConfigureMyServices(IServiceCollection services)
{
services.AddScoped<ICarService, CarService>();
}
same thing for database
public virtual void ConfigureDatabase(IServiceCollection services)
{
services.AddDbContext<CarContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CarDbConnection")));
}
public class TestStartup : Startup
{
private readonly Mock<ICarService> _carServiceMock;
public TestStartup(IConfiguration configuration) : base(configuration)
{
_carServiceMock = new Mock<ICarService>();
}
public override void ConfigureMyServices(IServiceCollection services)
{
services.AddSingleton(_carServiceMock.Object);
}
public override void ConfigureDatabase(IServiceCollection services)
{
services.AddDbContext<CarContext>(options => options.UseInMemoryDatabase("CarDb"));
services.AddTransient<DataSeed>();
}
}
TestFixture is using TestStartup
public TestFixture()
{
_server = new TestServer(new WebHostBuilder()
.UseStartup<TestStartup>()
.UseEnvironment("Development"));
Client = _server.CreateClient();
}
Inside my controller I'm using ICarService to fetch data. ICarService implementation using CarContext.
public class CarController
{
private readonly ICarService _carService;
public CarController(ICarService carService)
{
_carService = carService;
}
[HttpGet]
public async Task<IActionResult> Get([FromRoute] int id)
{
var contact = await _carService.GetAsync(id); // this is always null
}
}
Am I injecting DbContext properly? Am I missing something? How can I be sure that CarContext is properly set and used by mocked ICarService?
Aucun commentaire:
Enregistrer un commentaire