Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring boot @Value property is null in test cases

I want to get values from application.properties.

@ExtendWith(MockitoExtension.class)
public class CurrencyServiceTest {

    @Mock
    private OpenExchangeRatesClient openExchangeRatesClient;

    @Value("${openexchangerates.app.id}")
    private String appId;

    @Value("${openexchangerates.currency.base}")
    private String base;

...

The thing is that appId and base are null in tests. What is the reason for that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

@Value is spring annotation and spring injects the value for properties into Spring-managed beans

This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.

If you want this functionality working, you have to use @SpringBootTest annotation to load ApplicationContext, which is typically writing integration test

The @SpringBootTest annotation is useful when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.

You can also inject value while writing unit test cases using ReflectionTestUtils, like example shown here

@Before
public void setUp() {
    ReflectionTestUtils.setField(springJunitService, "securityKey", "it's a security key");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading