[英]Mock Service class that has Autowired dependencies
I have a Service class & a config class as below:我有一个服务 class 和一个配置 class 如下:
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:下面是 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.当我在服务 class 的 webClient 上运行此 class 时,出现 null 指针错误。 What could be the issue.
可能是什么问题。 I am new to JUnits.
我是 JUnits 的新手。 How do I write a proper JUnit for this.
我该如何为此编写正确的 JUnit。
The easiest way to make the class testable is to use constructor injection使 class 可测试的最简单方法是使用构造函数注入
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;
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.