如何在mockito / Junit中调用mock方法而不是real方法

时间:2017-06-26 00:16:53

标签: unit-testing testing junit automation mockito

我想在调用ClassA.mockMethod()方法时调用objOfClassB.realMethod()

public class ClassA{
     public static int mockMethod(String url, MySql sql){
        int res=0
        // do work
        return ;
    }

}

Definition of executeUpdate1()
class Veps{
    protected synchronized int realMethod(String url, MySql sql){
    ----
    -----
    }
}

public class VepsTest {
        public void setUp() throws Exception {

            veps = mock(Veps.class);

            when(objOfClassA.realMethod(any(String.class), any())).thenReturn(objOfClassB.mockMethod(any(String.class),any()));
         }
}


org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 4 recorded.
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

1 个答案:

答案 0 :(得分:1)

mockito清楚地报告错误:

  

参数匹配器的使用无效!预计有2个匹配器,4个记录。

您不应在任何Matcher子句中使用then* s。您的问题可以修复为:

when(veps.executeQuery1(any(String.class), any(MySql.class)))
     .thenReturn(DBConnection.mockExecuteQuery("??","??"));

when(veps.executeUpdate1(any(String.class), any()))
     .thenReturn(DBConnection.mockExecuteUpdate("??","??"));

但是出现了另一个问题:为什么你需要从数据库中查询结果?你可以简单地用一个常量来伪造结果:

when(veps.executeQuery1(any(String.class), any(MySql.class)))
     .thenReturn(1);
//               ^--- replace the constant 1 with yours

when(veps.executeUpdate1(any(String.class), any()))
     .thenReturn(1);
//               ^--- replace the constant 1 with yours

在测试中使用它之前,您需要进一步查看description