0

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?

Joseph Gagnon
  • 1,731
  • 3
  • 30
  • 63
  • I don't understand your question. Which class is mocked? And which constructor argument is null? – Simon Martinelli Jun 20 '19 at 14:05
  • 1
    or [How do I mock an autowired @Value field in Spring with Mockito?](//stackoverflow.com/q/23162777) – Tom Jun 20 '19 at 14:07
  • Your testing issue here show why field injection is flawed. You should consider refactoring your code to use constructor injection instead. – Tom Jun 20 '19 at 14:10
  • I tweaked my google search parameters and found the referenced SO posting. Thanks for all of the quick responses. D'oh! – Joseph Gagnon Jun 20 '19 at 14:12

0 Answers0