usr_11
usr_11

Reputation: 576

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?

Upvotes: 0

Views: 1900

Answers (2)

Beppe C
Beppe C

Reputation: 13893

ServiceClass should be define as Spring bean

@Configuration    
public class ServiceClass {

Upvotes: 0

Vikas
Vikas

Reputation: 7165

You can use ReflectionTestUtils setField

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

Upvotes: 3

Related Questions