I am trying to write unit tests for @Service annotated class. I have application.properties file set and a class to access the values.
@Component
@ConfigurationProperties
@PropertySource("classpath:application.properties")
public class ApplicationProperties {
private String first_name;
private String last_name;
private String base_url;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String firstName) {
this.first_name = firstName;
}
public String getLast_name() {
return last_name;
}
public void setFirst_name(String lastName) {
this.last_name = lastName;
}
public String getBase_url() {
return base_url;
}
public void setBase_url(String baseUrl) {
this.base_url = baseUrl;
}
}
and the test I wrote is like this
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { ApplicationProperties.class })
@TestPropertySource(locations="classpath:application.properties")
public class ServiceTests {
@Autowired
private ApplicationProperties applicationProperties;
@Before
private void initializeConfig() {
Mockito.when(applicationProperties.getFirst_name()).thenReturn("Karan");
}
@Test
public void sample_Test() {
MyService myService = new MyService();
String fName = myService.getUserFirstName();
assertEquals(fName, "Karan");
}
}
and the method myService.getUserFirstName is like this
@Service
public class MyService {
@Autowired
private ApplicationProperties applicationProperties;
public String getUserFirstName() {
return applicationProperties.getFirst_name();
}
}
I tried following ways provided in this tutorial and this, this and this stackoverflow questions. But it always have applicationProperties object null in the getUserFirstName method and throws null value exception.
Any suggestion what I am doing wrong.