Reputation: 574
I have a Service class & a config class as below:
public class MyService{
@Autowired
MyConfig myconfig;
@Autowired
private WebClient webClient;
private String result;
public String fetchResult(){
return webClient.get().uri(myConfig.getUrl()).retrieve().bodyToMono(String.class).block();
}
}
@ConfigurationProperties("prefix="somefield")
@Component
class MyConfig{
private String url;
//getter & setter
}
}
Below is the Junit:
@Runwith(MockitoJUnitRunner.class)
public class TestMe{
@InjectMocks
MyService myService;
@Test
public void myTest(){
when(myService.fetchResult().then return("dummy");
}
}
I am getting null pointer error when I run this class at webClient in Service class. What could be the issue. I am new to JUnits. How do I write a proper JUnit for this.
Upvotes: 0
Views: 211
Reputation: 24560
The easiest way to make the class testable is to use constructor injection
public class MyService{
private final MyConfig myconfig;
private final WebClient webClient;
private String result;
@AutoWired
MyService(
MyConfig myconfig,
WebClient webClient
) {
this.myconfig = myconfig;
this.webClient = webClient;
}
...
}
Upvotes: 1