如何解决实际上Mockito中的这个模拟错误与零交互

时间:2017-08-23 10:51:43

标签: 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 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());
     }
}  

我大部分时间都在查看源代码,但无法获得上述测试类中缺少的内容

1 个答案:

答案 0 :(得分:1)

在您的测试用例中,您尝试验证是否已调用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 :基于这些评论&#34;我可以测试xtractor.extractValues(),即使此调用不在Sample类中......好的,这里我将删除@Mock来自Xtractor,我如何测试xtractor.extractValues()&#34;期望的答案可能是:

@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
}