Java – Mockito: how to stub getter setter

javamockitotesting

I am kind of new to Mockito and I was wondering how I could stub a get/set pair.

For example

public interface Dummy {
     public String getString();
     public void setString(String string);
}

How can I make them behave properly: if somewhere in a test I invoke setString("something"); I would like getString() to return "something". Is that feasable or is there a better way to handle such cases?

Best Answer

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));