I’m encountering a NullReferenceException
in the SetInterval()
method of my ApiWorker
class when running a unit test. Below are the relevant parts of my code.
public ApiWorkerTests()
{
_mockLogger = new Mock<ILogger<ApiWorker>>();
_mockDbService = new Mock<IDatabaseService>();
_mockApiService = new Mock<IApiService>();
_mockConfig = new Mock<IConfiguration>();
_mockConfig.Setup(c => c[$"Authentication:CompanyKey"]).Returns("SomeKey");
_mockConfig.Setup(c => c[$"Authentication:VehicleKey"]).Returns("SomeKey");
_mockConfig.Setup(c => c["Interval"]).Returns("00:00:10");
_apiWorker = new ApiWorker(_mockApiService.Object, _mockLogger.Object, _mockConfig.Object, _mockDbService.Object);
}
[Fact]
public void ApiWorker_Initialization()
{
// Arrange & Act
var worker = new ApiWorker(_mockApiService.Object, _mockLogger.Object, _mockConfig.Object, _mockDbService.Object);
// Assert
Assert.NotNull(worker);
}
And here’s the ApiWorker
:
public ApiWorker(IApiService apiService, ILogger<ApiWorker> logger, IConfiguration config, IDatabaseService db)
{
_apiService = apiService;
_logger = logger;
_db = db;
_companyKey = config[$"Authentication:CompanyKey"] ?? throw new Exception("Company ID cannot be null");
_vehicleKey = config[$"Authentication:VehicleKey"] ?? throw new Exception("Vehicle ID cannot be null");
_config = config;
SetInterval();
}
private void SetInterval()
{
var intervalString = _config.GetValue<string>("Interval");
// Conversion to DateTime
}
Hard-coding the intervalString
to “00:00:10” makes the test pass, but I want to understand why the mock setup isn’t working as expected. The setup of the IConfiguration mock seems to be the issue.