Home > Enterprise >  Spring boot @Value property is null in test cases
Spring boot @Value property is null in test cases

Time:06-03

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?

CodePudding user response:

@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");
}
  • Related