Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito: how to stub getter setter

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?

like image 501
Guillaume Polet Avatar asked Apr 18 '12 20:04

Guillaume Polet


People also ask

What is Mockito stub method?

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.

What is stubbing JUnit?

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.

How to mock a method using Mockito?

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.


1 Answers

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)); 
like image 153
user2006754 Avatar answered Sep 19 '22 21:09

user2006754