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?
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
A stub is a controllable replacement for an existing dependency (or collaborator) in the system. By using a stub, you can test your code without dealing with the dependency directly. A mock object is a fake object in the system that decides whether the unit test has passed or failed.
With Mockito, you create a mock, tell Mockito what to do when specific methods are called on it, and then use the mock instance in your test instead of the real thing. After the test, you can query the mock to see what specific methods were called or check the side effects in the form of changed state.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With