0

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.

enter image description here

Karan
  • 752
  • 2
  • 13
  • 34
  • 1
    Have tried you making a `test/resources` directory and put a test copy of your `application.properties` in there? This might work depending on your set up. – Gavin Dec 20 '19 at 15:54
  • @Gavin, added the file as shown in updated image but still it is null. – Karan Dec 20 '19 at 16:02
  • follow this article https://reflectoring.io/unit-testing-spring-boot/ – Ryuzaki L Dec 20 '19 at 16:38

0 Answers0