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.properties
file with required value. - Created
application-test.properties
and 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