Search code examples
javaspring-bootjunitjunit4spring-boot-test

Null pointer exception while accessing property from application properties in Junit test


I have method which access property from application.properties & for which I am writing junit.

class ServiceClass{

@Value("${urlfromapplicationproperties}")
public String myUrl ;

public String getUrl(){
 return myUrl;
}
}

Below is test case:

@RunWith(SpringJunit4ClassRunner.class)
@PropertySource("classpath:test:properties")
public class ServiceClassTest {

@Mock 
ServiceClass serviceclass;

@Before
public void setup(){ MockitoAnnotations.initMocks(this);}

@Test
public myTestMethod(){

serviceclass.getUrl();
}
}

when I access the method its throwing null pointer. I have declared that property in application-test.yml too. what I am missing? any reference or answer to resolve this?


Solution

  • You can use ReflectionTestUtils setField

    @Before
    public void setup(){
        ReflectionTestUtils.setField(serviceclass, "myUrl", "http://testurl");
        MockitoAnnotations.initMocks(this);}
    }