有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何解决实际上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) 个答案

  1. # 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:基于这些注释“即使此调用不在示例类中,我是否可以测试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
    }