Java 具有自动关联依赖项的模拟服务类
我有一个服务类&a配置类,如下所示:Java 具有自动关联依赖项的模拟服务类,java,junit,nullpointerexception,mockito,junit4,Java,Junit,Nullpointerexception,Mockito,Junit4,我有一个服务类&a配置类,如下所示: public class MyService{ @Autowired MyConfig myconfig; @Autowired private WebClient webClient; private String result; public String fetchResult(){ return webClient.get().uri(myConfig.getUrl()).retrieve().bodyToMono(Stri
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上运行此类时,我遇到空指针错误。
可能是什么问题。我是个新手。
如何为此编写适当的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;
}
...
}
你提出的测试毫无意义。您只在测试对象上存根了一个方法。您得到了NPE,并且正确地说,您使用未初始化的成员在测试对象上调用了一个方法。NPE还涉及到另一个问题:您试图在一个非模拟对象上存根方法!这对我有用。有一个疑问,如果我在MyService类中有stepExecution,我如何从Junit中调用它?它通过
myService.stepExecution
提供NPE.Just。我看了你的问题,你的测试把myService当成了一个模拟。您应该清楚哪些内容需要模拟,哪些内容需要测试。但是现在在服务类中使用的spring批处理的stepexecution上陷入了NPE。你已经读过了吗?是的,我几分钟前读过了,并按照文档中的建议用MetaDataInstanceFactory解决了它。非常感谢你的努力和时间。