0

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?

usr_11
  • 548
  • 10
  • 31
  • this would help https://stackoverflow.com/questions/23162777/how-do-i-mock-an-autowired-value-field-in-spring-with-mockito – Sri Sep 20 '20 at 16:28

2 Answers2

3

You can use ReflectionTestUtils setField

@Before
public void setup(){
    ReflectionTestUtils.setField(serviceclass, "myUrl", "http://testurl");
    MockitoAnnotations.initMocks(this);}
}
Vikas
  • 6,868
  • 4
  • 27
  • 41
0

ServiceClass should be define as Spring bean

@Configuration    
public class ServiceClass {
Beppe C
  • 11,256
  • 2
  • 19
  • 41