bcorso
bcorso

Reputation: 47088

Mockito: verify any() parameter is the same

I would like to do something like:

MyEnum myEnum = any();  // This is not allowed throws InvalidUseOfMatchersException
MyClassUtils.method(myClass, myEnum);

// Verify MyClassUtils.method(MyEnum) calls myClass.method(MyEnum)
verify(myClass).method(myEnum);

The idea is that I don't care which enum is passed into MyClassUtils#method(MyEnum), as long as it's the same enum that gets passed into MyClass#method(MyEnum).

QUESTION: Is there a Mockito way for me to test this without having to specify a specific enum?


I know I could just use:

MyEnum myEnum = MyEnum.FIRST;

But, this seems misleading because it suggests that I'm testing something specific to MyEnum.FIRST.

Upvotes: 1

Views: 406

Answers (1)

Daniel Pryden
Daniel Pryden

Reputation: 60957

You're thinking about your test backwards: the characteristic of your MyClassUtils object that you're trying to verify is: "no matter what instance of MyEnum is passed into it, it always calls myObject.method with that same instance".

Loosely translated, this is:

∀ x: x ← MyEnum

   where o ← MyClass

   MyClassUtils.method(o, x) ⇒ o.method(x)

(Excuse my terrible math editing skills here.)

To test this characteristic exhaustively, you need to verify it for every possible value of MyEnum. You can easily do this by using a for loop, or you could use something like the JUnit Parameterized runner.

However, an exhaustive test is probably not warranted here. Instead, simply select a representative subset which should exercise all expected behaviors of your system under test. It's possible that testing with any arbitrarily chosen element of MyEnum is sufficient, and if so there is no harm in doing just that.

One common way to do that is to select a "sample" value and store it in a constant in your test class. By being explicit, debugging is easier: if it later turns out that your representative value was not representative after all, it should be easier to debug if you have the value right there.

TL;DR: a single arbitrarily chosen value should be fine for your test. If it isn't, the solution is to be more exhaustive in your testing, not to be more arbitrary.

Upvotes: 1

Related Questions