Java 如何解决Mockito中没有与此模拟错误交互的问题
我试图运行测试类,但是抛出了一个错误,即实际上没有交互Java 如何解决Mockito中没有与此模拟错误交互的问题,java,junit,mockito,Java,Junit,Mockito,我试图运行测试类,但是抛出了一个错误,即实际上没有交互 class Xtractor{ void extractValues(request,Map m1, Map m2,Map m3){ //doesSomething.. } } class Sample{ public void extractMap(){ x.extractValues(request,m1,m2,m3); } } class SampleT
class Xtractor{
void extractValues(request,Map m1, Map m2,Map m3){
//doesSomething..
}
}
class Sample{
public void extractMap(){
x.extractValues(request,m1,m2,m3);
}
}
class SampleTest{
@Mock
Xtractor xtractor;
@Mock
Sample sample;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
xtractor=mock(Xtractor.class);
ArgumentCaptor<Map> m1= ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<Map> m2= ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<Map> m3= ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<HttpServletRequest> request=
ArgumentCaptor.forClass(HttpServletRequest.class);
}
@Test
public void testmapExtractor(){
Mockito.verify(xtractor).extractValues( request.capture(),m1.capture(),m2.capture(),m3.capture());
}
}
我大部分时间都在查看源代码,但无法获得上面测试类中缺少的内容。在您的测试用例中,您试图验证是否调用了xtractor.extractMap,但在测试中的任何地方都没有调用该方法。另一方面:extractMap(您在测试用例中引用)和ExtractValue(您在示例代码中显示)之间存在一些混淆 假设为该示例提供了一个Xtractor实例,并且该示例公开了一个使用该Xtractor实例的公共方法,那么您将在该示例上测试该公共方法,如下所示:
public class Sample {
private Xtractor xtractor;
public Sample(Xtractor xtractor) {
this.extractor = extractor;
}
public void doIt(HttpServletRequest request, Map m1, Map m2, Map m3) {
x.extractValues(request,m1,m2,m3);
}
}
@Test
public void testmapExtractor() {
// create an instance of the class you want to test
Sample sample = new Sample(xtractor);
// invoke a public method on the class you want to test
sample.doIt();
// verify that a side effect of the mehod you want to test is invoked
Mockito.verify(xtractor).extractMap(request.capture(), m1.capture(), m2.capture(), m3.capture());
}
虽然这个例子看起来有点奇怪,但它仍然可以工作。您有一个名为extractValues的方法,它的类型是void。。。您的问题中提供的示例类没有主体等,但在本例中基本元素已就位,即
莱克斯特被嘲笑了
模拟的Xtractor实例被传递到Sample中
样品进行了测试
已验证从Sample到Xtractor的二次调用
编辑1:基于这些注释,我可以测试xtractor.extractValues吗?即使此调用不在示例类中。。。好的,这里我将从Xtractor中删除@Mock,如何测试Xtractor.extractValues所需的答案可能是:
@Test
public void testmapExtractor() {
// create an instance of the class you want to test
Xtractor xtractor = new Xtractor();
// invoke a public method on the class you want to test
xtractor.extractValues();
// assert
// ...
// without knowing exactly what extractValues does it's impossible to say what the assert block should look like
}
这里的Sample、Xtractor和SampleTest都是三个文件。您能告诉我代码中的具体问题在哪里吗?问题是您的测试用例从不调用xtractor.extractValues,因此您尝试验证该调用失败。因此,我提供了一个调用xtractor.extractValues的示例测试用例,并提供了一个项目符号列表,描述了test/mock/verify的原理。即使此调用不在示例类中,我也可以测试xtractor.extractValues吗?是的,您可以,但如果您想要测试xtractor.extractValues,那么您将不想模拟xtractor。这里可能对mock的作用有误解。mock用于促进测试,但如果您想测试类A,则不能模拟类A,否则您的测试将无效。好的,这里我将从Xtractor中删除@mock,如何测试Xtractor.extractValues