同一类中的模拟方法 [英] mock methods in same class

查看:64
本文介绍了同一类中的模拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito在与我为其编写测试的同一类中模拟方法.我在SO上看到了其他答案(

I am using Mockito to mock a method in the same class for which I am writing test. I have seen other answers on SO (Mocking method in the same class), but probably I am misunderstanding them, since I running into issues.

 class Temp() {

    public boolean methodA(String param) {

         try {

             if(methodB(param))
                   return true;

             return false;
         } catch (Exception e) {
               e.printStackTrace();
         }
    }
 }

我的测试方法:

 @Test
 public void testMethodA() {

    Temp temp = new Temp();
    Temp spyTemp = Mockito.spy(temp);

    Mockito.doReturn(true).when(spyTemp).methodB(Mockito.any()); 
    boolean status = temp.methodA("XYZ");

    Assert.assertEquals(true, status);
 }

但是由于执行methodB的定义,我得到了期望. 我的理解是,使用spyTemp会嘲笑methodB的定义.但是,情况似乎并非如此.

I however get the expection printed out because definition of methodB gets executed. My understanding is definition of methodB would get mocked by using spyTemp. However that does not appear to be the case.

有人可以解释我要去哪里吗?

Can someone please explain where I am going wrong?

推荐答案

第一个问题是,您必须使用spyTest对象才能从Mockito获得期望.这里与测试不同. spyTemp是由Mockito对象temp包装的.

First issue is that you have to use spyTest object to expect something from Mockito. Here it is not the same as test. spyTemp is an wrapped by Mockito object temp.

另一个问题是您仅对methodB()进行存根,但是尝试运行methodA().是的,在实现methodA()时,您调用methodB(),但在this.methodB()处而不是在spyTemp.methodB()处调用.在这里,您必须了解,仅当在temp实例上调用模拟时,该模拟才有效.它由Mockito代理包装,可以捕获您的调用,如果您覆盖了某些方法,它将调用您的新实现而不是原始实现.但是由于调用了原始方法,因此在其中您对Mockito代理一无所知.因此,仅当您运行spyTemp.methodB()

Another issue is that you stub only methodB(), but trying to run methodA(). Yes in your implementation of methodA() you call methodB(), but you call at this.methodB(), not as spyTemp.methodB(). Here you have to understand that mocking would work only when you call it on the instance of temp. It's wrapped by Mockito proxy which catch your call and if you have overriden some method it would call your new implementation instead of original. But since original method called, inside it you know nothing about Mockito proxy. So your "overriden" method would be called only when you run spyTemp.methodB()

这应该有效:

Mockito.doReturn(true).when(spyTemp).methodB(Mockito.any()); 
boolean status = spyTemp.methodB("XYZ");

这篇关于同一类中的模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆