Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Mockito claiming method called twice

  • 16-10-2015 11:02AM
    #1
    Closed Accounts Posts: 6,075 ✭✭✭


    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.<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.<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()?


Comments

  • Closed Accounts Posts: 6,075 ✭✭✭IamtheWalrus


    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.


Advertisement