-3

Can you make assumptions with Mockito?

If the method's not invoked, this would throw AssertionError and make the test fail.

then(mock).should().doSomething();

Instead, I want the test to be skipped, similar to assumeTrue() (JUnit) or assumeThat() (AssertJ).

Mockito 4.11.0.

6
  • It is unclear what you are asking or what the problem is. Please edit your question to include a more detailed description of the problem you have. Commented Sep 30 at 7:38
  • @Progman I believe it's totally clear: "I want the test to be skipped, similar to assumeTrue() (JUnit) or assumeThat() (AssertJ)" Commented Sep 30 at 7:41
  • You won't know that the method is not invoked until the end of the test. And that's what you can use verify(mock, never()).should() for, or perhaps even verifyNoInteractions(mock) or verifyNoMoreInteractions(mock). Commented Sep 30 at 7:47
  • @RobSpoor those methods assert, not assume Commented Sep 30 at 7:58
  • 1
    Yes, but you cannot assume beforehand that a method will not be invoked. The test has already run. If you want the test to be marked as skipped, then perhaps you can use try { verify(mock, atLeastOnce()).should(); } catch (AssertionError _) { assumeTrue(false, "should() hasn't been invoked"); }. I'm guessing the error to catch, you may need to change it. Commented Sep 30 at 8:38

1 Answer 1

1

You could catch the exception from verify and rethrow it as TestAbortedException:

try {
  verify(mockObject).doSomething();
} catch (final MockitoAssertionError ex) {
  throw new TestAbortedException("Method doSomething not called", ex);
}

(Although I don't know why you'd want to not fail the test in this case. If the method call is not required, don't verify/assert it at all?)

Extract a utility method to make this logic reusable:

class VerificationAssumptions {
  private VerificationAssumptions() {}

  static void assumeVerify(final String message, final Runnable verification) {
    try {
      verification.run();
    } catch (final MockitoAssertionError ex) {
      throw new TestAbortedException(message, ex);
    }
  }
}

and then use:

VerificationAssumptions.assumeVerify(
  "Method doSomething not called",
  () -> verify(mockObject).doSomething());

(you might be able to implement a nicer API, such as assumeVerify(mockObject).doSomething(), but I'll leave this to the reader ;))

Sign up to request clarification or add additional context in comments.

2 Comments

Well, I need to make sure X happened before proceeding with the test of Y (the test of Y should not fail if X does)
Is this then not a better option? junit-pioneer.org/docs/disable-if-test-fails

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.