Background:
- Java 8 (1.8.0_201)
- Spring Boot
- Mockito (2.23.4)
I have a number of JUnit tests written for our software application and am in the middle of refactoring/fixing test failures due to modifications to the code base.
I have run into a problem I don't know how to solve. I'll include code snippets to hopefully illustrate what I have.
The problem is that a test fails with a NPE because a mocked bean's constructor argument is null. The argument is injected with a value (in the regular run-time environment) via a @Value
annotation. I don't know how to provide that argument a value in the unit test.
Examples:
In the SUT class:
@Value("${logsDir}${file.separator}${service.name}_${service.id}_${service.container.type}_stats.json")
private String statsFilePath;
...
@Override
public void initialize() throws RSTServiceException {
statsWriter = new StatsWriter<>(new StatsSerializer(ServiceStats.class), statsFilePath);
}
In StatsWriter.java
:
public StatsWriter(StdSerializer<T> serializer, String filePath) throws RSTServiceException {
File statsFile = new File(filePath);
}
In the unit test:
@Test
public void testInitialize() {
try {
// Exercise SUT.
service.initialize();
} catch (RSTServiceException e) {
fail(e.getMessage());
}
...
}
So, in the unit test, statsFilePath
is null and the call to the File
constructor fails with a NPE. How do I provide a non-null value to this field?