Hec*_*tor 5 java testing mockito
我正在使用mockito进行测试,但我遇到了这个问题:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at cl.gps.tms.planifications.planification.test.PlanificationCreateTest.setUp(PlanificationCreateTest.java:68)
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"));
...
PlanificationCreateTest使用SimpleQueryBus创建一个通用查询,其中de first参数指示返回的对象类型,第二个参数是查询的过滤器.
我想要存根SimpleQueryBus类(外部库)返回null(仅限现在)
SimpleQueryBus代码
public class SimpleQueryBus implements QueryBus {
    public <T, R> R handle(Class<R> clazz, T query) throws Exception {
    ...
    }
}
我的测试代码
public class PlanificationCreateTest {
    private QueryBus queryBus;
    @Before
    public void setUp() throws Exception {
        queryBus = Mockito.mock(SimpleQueryBus.class);
        when(queryBus.handle(VehicleCollection.class, any(GetVehicle.class))).thenAnswer(null);
        ....
    }
}
更新(已解决):
public class PlanificationCreateTest {
    private QueryBus queryBus;
    @Before
    public void setUp() throws Exception {
        queryBus = Mockito.mock(SimpleQueryBus.class);
        // first example
        when(queryBus.handle(any(Class.class), isA(VehicleAvailable.class))).thenReturn(null);          
        // second example
        vehicle = new VehicleCollection("001", "name", "tag", "brand", "model");            
        when(queryBus.handle(any(Class.class), isA(GetVehicle.class))).thenReturn(vehicle);
        ....
    }
}
谢谢...
squ*_*lsv 11
发生这种情况是因为您正在使用类型any()的真实参数.VehicleCollection.classClass<VehicleCollection>
改变就像下面一样,你应该没问题:
 when(queryBus.handle(any(VehicleCollection.class), any(GetVehicle.class))).thenAnswer(null);
Mockito解释了原因:http://mockito.googlecode.com/svn/tags/1.7/javadoc/org/mockito/Matchers.html
如果您使用参数匹配器,则所有参数都必须由匹配器提供.
例如:(示例显示验证,但同样适用于存根):
Run Code Online (Sandbox Code Playgroud)// Correct - eq() is also an argument matcher verify(mock).someMethod(anyInt(), anyString(), eq("third argument")); // Incorrect - exception will be thrown because third argument is given without argument matcher. verify(mock).someMethod(anyInt(), anyString(), "third argument");
| 归档时间: | 
 | 
| 查看次数: | 18931 次 | 
| 最近记录: |