There is a @Value annotated constant, which is not getting initialized when running test, it throws NullPointerException when it is required inside constructor.
Sample Class to be tested:
class TestClass {
@Value("${test.value1}")
private String value1;
private final TestTemplate testTemplate;
public TestClass(TestTemplateBuilder builder) {
testTemplate = builder.someMethod(value1).build();
}
---
}
Sample Test Class:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = TestClass.class)
@SpringBootTest
class TestClassTest {
@MockBean
TestTemplateBuilder builder;
@Autowired
TestClass testClass = new TestClass(testTemplate);
@Before
public void setUp() {
ReflectionTestUtils.setField(testClass, "value1", "VALUE");
Mockito.when(builder.build()).thenReturn(new TestTemplate());
}
---
}
Things tried, but nothing worked:
- I have created
application.propertiesfile with required value. - Created
application-test.propertiesand added@TestPropertySource(locations="classpath:application-test.properties"). @SpringBootTest(properties = { "test.value1=VALUE" })
I have tried some other things also, but what i got is NullPoiterException at someMethod(value1).
Versions:
- Java: 1.8
- Springboot: 2.1.17
- Junit: 4.12
- Mockito: 2.23.4
The reason you are getting NullPointerException is that the value injection occurs after the constructor call. To prevent this you can use spring life cycle hooks to initialize your class after the constructor call.