Lonelyisland
Lonelyisland

Reputation: 51

How to overwrite a settermethod in Mockito?

I can't seem to figure out how to mock a simple setter method using Mockito. I have the following class:

class MyClass {
    private SomeObject someObject;

    public void setSomeObject(SomeObject someObject) {
        this.someObject = someObject;
    }

    public someObject getSomeObject() {
        return someObject;
    }
}

Now I just want that when "setSomeObject" is called that a new instance of "SomeObject" is set. Also the parameter within the setter should be ignored.

I need something like this:

MyClass mockedClass = mock(MyClass.class);
when(mockedClass.setSomeObject([ignoreWhatsInHere]))
    .then(mockedClass.setSomeObject(new SomeObject();

However, I can't seem to get the syntax working for this. I can only get the mocks to work using getters(), because then I can return something. But I can't figure out how to do the same for setters().

All help appreciated.

Upvotes: 5

Views: 4770

Answers (1)

RoryB
RoryB

Reputation: 1047

You should be able to use the doThrow()|doAnswer()|doNothing()|doReturn() family of methods to perform a suitable action when testing methods that return void including setters. So instead of

when(mockedObject.someMethod()).thenReturn(something)

you would use doAnswer() to return a custom Answer object, although it's not terribly elegant, and you might be better off using a stub:

doAnswer(new Answer() { 
    public Object answer(InvocationOnMock invocation) {
          //whatever code you want to run when the method is called
          return null;
  }}).when(mockedObject).someMethod();
}

If you are trying to return different values from the same getter call, you may also want to look at mockito's consecutive stubbing calls, which will allow you to, for example, throw an error for the first call of a method, and then return an object from the second call.

see http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#12 for more details on both of these.

Upvotes: 5

Related Questions