HungryBird
HungryBird

Reputation: 1147

cannot inject the @value defined in application.properties when use mock test

How can I inject the value defined in application.properties when I do a mockito test.

Service.java

@Override
public String getUseLanguage() {
    return applicationProperties.getLanguage();
}

ApplicationProperties.java

public class ApplicationProperties {

    @Value("${language}")
    private String Language;

    public String getLanguage() {
        return Language;
    }

application.properties

Language = EN;

My test case:

@RunWith(MockitoJUnitRunner.class)
public class TimChannelServiceTest {
@Mock
private ApplicationProperties applicationProperties;

@InjectMocks
private Service Service;

@Test
public void getUseLanguage(){
    assertEquals(applicationProperties.getLanguage(),Service.getUseLanguage());
    }
}

it seems @Value is not injected with the ApplicationProperties, both applicationProperties.getLanguage() and Service.getUseLanguage() are null.

Could anyone tell me how to handle this problem

Upvotes: 2

Views: 2377

Answers (3)

Aditya Narayan Dixit
Aditya Narayan Dixit

Reputation: 2119

You need to load spring context for @value to work. Annotate your class with @SpringBootTest. Also instead of mocking your ApplicationProperties autowire it. And have language property defined in your test properties file.

Upvotes: 1

davidxxx
davidxxx

Reputation: 131336

You mock the applicationProperties field in your test and you don't provide any behavior. That makes sense that methods invoked on return null.
Besides, why do you mock if you want that properties be injected as it should be ?

To test the application.properties values, annotate your class with @SpringBootTest that will load the Spring context and in this way the environment properties will be loaded.

Upvotes: 1

Rishi Saraf
Rishi Saraf

Reputation: 1812

If you are talking about spring @Value than you have to run your test cases with @RunWith(SpringJUnit4ClassRunner.class) annotations along with context file which will inject Application properties class.

    @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:test-context.xml")
public class MyTest {
    }

However in you case you are mocking hence you cannot expect it to provide spring utilities.

Upvotes: 1

Related Questions