How to overwrite settermethod in Mockito?

I can't 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 a new instance of "SomeObject" to be installed when calling "setSomeObject". You should also ignore the parameter inside the setter.

I need something like this:

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

However, I cannot get the syntax to work for this. I can get mocks to work with getters (), because then I can return something. But I can't figure out how to do the same for seters ().

All help was appreciated.

+6
source share
1 answer

You should be able to use the doThrow()|doAnswer()|doNothing()|doReturn() family of methods to perform the appropriate action when testing methods that return void, including seters. Therefore, instead of

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

you would use doAnswer() to return a custom response object, although it is not very 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 request, you can also look at consecutive consecutive calls to mockito, which will allow you, for example, throw an error for the first method call and then return the object from the second call.

see http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#12 for more information on the two.

+5
source

All Articles