如何解决具有自动装配依赖项的模拟服务类
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
}
}
下面是 Junit:
@Runwith(MockitoJUnitRunner.class)
public class TestMe{
@InjectMocks
MyService myService;
@Test
public void mytest(){
when(myService.fetchResult().then return("dummy");
}
}
当我在服务类中的 webClient 上运行此类时,出现空指针错误。 可能是什么问题。我是 JUnits 的新手。 我如何为此编写合适的 JUnit。
解决方法
使类可测试的最简单方法是使用构造函数注入
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;
}
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。