6

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?

0

1 Answer 1

6

@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");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.