ceoboy
ceoboy

Reputation: 21

Mockito claiming method called twice

I am running a test on my class using Mockito. The test verifies that a method called postMessage(destination, messageString) is called.

My test aims to verify that, depending on the message content, postMessage() is either called once or zero times.

The issue I have is that in my class, I have 2 calls to postMessage(). The difference between the 2 calls is the destination - the calls send a message to 2 different destinations.

e.g.

1. postMessage(destination-1, message)

2. postMessage(destination-2, message)

When I call verify with 1 times, like so

//actually called twice because of destination-1 and destination-2
verify(sender, times(1)).postMessage(Mockito.<javax.jms.Destination>.any(), Mockito.<String>.any());

the actual number is 2. I know the number 2 is right because it's called twice, but I want to isolate a test on only the method called with destination-2.

Also, when I want to verify that postMessage() is called zero times (message not sent), my test will class will rightly claim that postMessage() was called once - this is because it was actually called for destination-1.

//actually called once because of destination-1
verify(sender, times(0)).postMessage(Mockito.<javax.jms.Destination>.any(), Mockito.<String>.any());

So my question is - how do I isolate my test to testing exactly what I want and not the behaviour of my first call to postMessage()?

Upvotes: 1

Views: 1585

Answers (1)

ceoboy
ceoboy

Reputation: 21

As per @Tom's suggestion: Why do you use Mockito..any() if you don't want to match any Destination? Use eq(destXYZ) instead with "destXYZ" being your destination to test.

Replacing:

//actually called twice because of destination-1 and destination-2
verify(sender, times(1)).postMessage(Mockito.<Destination>.any(), Mockito.<String>.any());

with

Destination myDest = mock(Destination.class);

//actually called twice because of destination-1 and destination-2
verify(sender, times(1)).postMessage(myDest, Mockito.<String>.any());
worked.

passed my test.

Upvotes: 1

Related Questions