Can't Tell
Can't Tell

Reputation: 13426

Mockito error : org.mockito.exceptions.misusing.InvalidUseOfMatchersException

I have the below code

public void testInitializeButtons() {
        model.initializeButtons();
        verify(controller, times(1)).sendMessage(
                eq(new Message(eq(Model.OutgoingMessageTypes.BUTTON_STATUSES_CHANGED),
                        eq(new ButtonStatus(anyBoolean(), eq(false), eq(false), eq(false), eq(false))),
                        anyObject())));
    }

which throws the following exception

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
1 matchers expected, 9 recorded.
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.
    at se.cambiosys.client.medicalrecords.model.MedicalRecordPanelModelTest.testInitializeButtons(MedicalRecordPanelModelTest.java:88)

Can someone point to me how to write the test correctly?

Upvotes: 5

Views: 7373

Answers (3)

codebox
codebox

Reputation: 20254

The value inside sendMessage should just be a regular Message instance, you don't need to use the 'eq' call, similarly inside the ButtonStatus constructor, just use regular objects - you probably want somthing like this:

verify(controller, times(1)).sendMessage(
            new Message(Model.OutgoingMessageTypes.BUTTON_STATUSES_CHANGED,
                    new ButtonStatus(false, false, false, false, false),
                    <something else here>);

Upvotes: 2

Flavio
Flavio

Reputation: 11977

You can't do that: eq() can be used only for the mocked method parameters, not inside other objects (like you did in the constructor of Message). I see three options:

  • Write a custom matcher
  • Use an ArgumentCaptor, and test the properties of the Message with asserts()
  • Implement equals() in the Message class in order to test equality with another Message, based upon the fields you actually want to verify.

Upvotes: 6

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

You cannot nest matchers like this (although it would be awesome):

eq(new Message(eq(Model.OutgoingMessageTypes.BUTTON_STATUSES_CHANGED)

When you are using eq, the matcher simply uses equals() to compare what was passed to mock and what you are providing in verify(). That being said you should either implement your equals() method to compare only relevant fields or use custom matcher.

As a rule of thumb: you should have the same number of matchers as the number of arguments - or 0.

Upvotes: 3

Related Questions