1

I am getting InvalidUseOfMatchersException on a different test than the one using Matchers

The below two tests are running fine individually but when running together, after the first test passes successfully, second test is failing and throwing InvalidUseOfMatchersException pointing to first test

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

@Test public void testCalculateB() { assertTrue(BigDecimal.valueOf(8000).compareTo(calculator.calculateB(12)) == 0);
}

This is the exception in stack trace org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced or misused argument matcher detected here:

TestClass.shouldThrowExceptionWhenInputNull

According to the exception, first test should fail but its passing and second test is failing. Individually both these tests are passing successfully

1 Answers1

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

This isn't a valid use of Matchers. Mockito only uses any and eq when used with when or verify, as a means of matching invocations that tell Mockito what to return or what calls should have been recorded. You'll need to call calculateA with specific values, such as calculator.calculateA(1, 2, 3, null);.

Mockito matchers 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 from an @After method:

@After public void validateMockito() {
  Mockito.validateMockitoUsage();
}
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251