在Mockito中获取InvalidUseOfMatchersException

时间:2018-01-14 04:57:33

标签: mockito

我写过这个java方法:

public int run(String jobName) {
}

我写了这个测试代码:

@Test
public void testBatchStatusUpdateWithOneCompleteStatus() {

    Set<BatchEntity> staleBatch = createStaleBatch();
    Set<Integer> activeBatch = createActiveBatch();


    when(batchRepository.findBatchIdByStateIn(
            (Arrays.asList(BatchStates.IN_PROGRESS,
                    BatchStates.INTENT_MARKED)))).thenReturn(staleBatch);
    when(listingRepository.findBatchId()).thenReturn(activeBatch);

    Assert.assertEquals(batchStatusUpdate.run(Mockito.any(String.class)), 1);
    Mockito.verify(batchRepository,Mockito.times(2)).save(Mockito.any(BatchEntity.class));
}

运行

时出现以下错误
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:  Invalid use of argument matchers! 0 matchers expected, 1 recorded: at backgroundjob.BatchStatusUpdateTest.testBatchStatusUpdateWithOneCompleteStatus 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"));

有关更多信息,请参阅Matchers类的javadoc。

当run方法具有字符串参数时,我收到此错误。当我从run方法中删除字符串参数时,传递测试用例。

1 个答案:

答案 0 :(得分:0)

Mockito.any()创建一个匹配器,在指定模拟时或使用Mockito.verify()验证呼叫时使用。它们作为您正在测试的方法的参数没有意义。您的通话应更改为使用实际字符串,例如Assert.assertEquals(batchStatusUpdate.run("some value"), 1);而不是Assert.assertEquals(batchStatusUpdate.run(Mockito.any(String.class)), 1);