Mockito: how to stub getter setter

I've found that this works fine:

doAnswer(answer -> when(dummy.getString()).thenReturn((String) answer.getArguments()[0]))
    .when(dummy).setString(any());

I have to use the doAnswer(..).when(..) because the setter is a void method. When the setter is called with an object the getter will be set up to respond with the same object.

Very useful when you've got an interface, but no implementations.


I can think of three possible approaches.

  1. Don't use HttpServletRequest directly in your application; make a wrapper class for it, and have an interface for the wrapper class. Wherever you currently use HttpServletRequest in the application, use the interface instead. Then in the test, have an alternative implementation of this interface. Then, you don't need a Mockito mock at all.

  2. Have a field in your test class that stores the value that you have set the String to. Make two Mockito Answer objects; one that returns the value of this field when getString is called, and another that sets the value of this field when setString is called. Make a mock in the usual way, and stub it to use both of these answers.

  3. Make an abstract class (which can be a static inner class of your test class) that implements the HttpServletRequest interface, but has the field that you want to set, and defines the getter and setter. Then mock the abstract class, and pass the Mockito.CALLS_REAL_METHODS in as a default answer. When you call the getter or the setter on the mock, the real method will kick in, which is the behaviour you want.

Hopefully, one of these three alternatives will meet your needs.


I also wanted the getter to return the result of the recent setter-call.

Having

class Dog
{
    private Sound sound;

    public Sound getSound() {
        return sound;
    }
    public void setSound(Sound sound)   {
        this.sound = sound;
    }
}

class Sound
{
    private String syllable;

    Sound(String syllable)  {
        this.syllable = syllable;
    }
}

I used the following to connect the setter to the getter:

final Dog mockedDog = Mockito.mock(Dog.class, Mockito.RETURNS_DEEP_STUBS);
// connect getter and setter
Mockito.when(mockedDog.getSound()).thenCallRealMethod();
Mockito.doCallRealMethod().when(mockedDog).setSound(Mockito.any(Sound.class));