不同测试方法的 InvalidUseOfMatchersException

InvalidUseOfMatchersException on a different test method

我在与使用匹配器的测试不同的测试中遇到 InvalidUseOfMatchersException

下面的两个测试单独 运行 很好,但是当 运行 在一起时,第一个测试成功通过后,第二个测试失败并抛出 InvalidUseOfMatchersException 指向第一个测试

@Test(expected = InputException.class) public void shouldThrowExceptionWhenInputNull() { calculator.calculateA(any(), any(), any(),eq(null)); }

@测试 public void testCalculateB() { assertTrue(BigDecimal.valueOf(8000).compareTo(calculator.calculateB(12)) == 0);<br> }

这是堆栈跟踪中的异常 org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced or misused argument matcher detected here:

TestClass.shouldThrowExceptionWhenInputNull

根据异常情况,第一个测试应该失败,但它通过了,第二个测试失败了。单独这两项测试都成功通过

calculator.calculateA(any(), any(), any(), eq(null));

这不是 Matchers 的有效使用。 Mockito 仅在与 whenverify 一起使用时使用 anyeq 作为 匹配调用 的一种方式,告诉 Mockito 要做什么return 或者应该记录哪些通话。您需要使用特定值调用 calculateA,例如 calculator.calculateA(1, 2, 3, null);.

来自 @After 方法的 Mockito 匹配器 work via side effects, so the only time that Mockito can throw an exception is the next time you interact with Mockito. This might be another method, but you can help ensure that those are local by using MockitoRule, MockitoJUnitRunner, or by adding a call to validateMockitoUsage

@After public void validateMockito() {
  Mockito.validateMockitoUsage();
}