我正在尝试运行测试类,但实际上引发了零交互的错误。

 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与示例代码中显示的extractValues之间有些混淆)。

假定为Sample提供了Xtractor的实例,并且Sample公开了使用Xtractor实例的公共方法,那么您可以在Sample上测试该公共方法,如下所示:

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 ...在您的问题中提供的Sample类没有正文等),但该示例仍可以工作,但基本步骤已在其中这个例子


Xtractor被嘲笑
Xtractor的模拟实例传递到Sample
Sample已测试
已验证从SampleXtractor的辅助呼叫


编辑1:基于这些注释“即使这个调用不在Sample类中,我也可以测试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
}

09-26 09:40