gpt4 book ai didi

java - Mockito 问题 - InvalidUseOfMatchersException

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:47 26 4
gpt4 key购买 nike

我正在使用 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 创建通用查询,其中第一个参数指示返回的对象类型,第二个参数是查询的过滤器。

我想要 stub 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);

....
}
}

谢谢...

最佳答案

发生这种情况是因为您正在使用 any()连同实际参数 VehicleCollection.class类型 Class<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

If you are using argument matchers, all arguments have to be provided by matchers.

E.g: (example shows verification but the same applies to stubbing):

    // 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");

关于java - Mockito 问题 - InvalidUseOfMatchersException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24937539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com