How do I conduct the Dependency Injection in Integration Test?
Calling the departmentRepository
or departmentAppService
, is giving me null
and error below.
public class DepartmentAppServiceTest
{
public SharedServicesContext context;
public IMapper mapper;
public IRepository<Department, int> departmentRepository;
public IDepartmentAppService departmentAppService;
public DepartmentAppServiceTest()
{
ServiceCollection services = new ServiceCollection();
services.AddTransient<IRepository<Department>, BaseRepository<Department>>();
services.AddTransient<IDepartmentAppService, DepartmentAppService>();
debugging and setting breakpoints, both calling this repository or app service are null,
new method
[Fact]
var departmentDto = await departmentAppService.GetDepartmentById(2);
Constructors for App Service
DepartmentAppService(departmentRepository, mapper)
DepartmentRepository(dbcontext)
Error:
Message: System.NullReferenceException : Object reference not set to an instance of an object.
For our integration tests we programatically startup the application and use HttpClient to make calls against the API Endpoints. This way your app runs through the whole Startup process and dependency injection works like a charm.
Here is an Example of the Server Startup and client creation, it can be reused for multiple tests:
_server = new TestServer(new WebHostBuilder()
.UseEnvironment("Testing")
.UseContentRoot(applicationPath)
.UseConfiguration(new ConfigurationBuilder()
.SetBasePath(applicationPath)
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.Testing.json")
.Build()
)
.UseStartup<TestStartup>());
_client = _server.CreateClient();
// Act
var response = await _client.GetAsync("/");
// Assert
response.EnsureSuccessStatusCode();
It's also documented by microsoft like this with the HttpClient:
https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-2.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With