user15006167
user15006167

Reputation: 234

JUnit 5 and Mockito: Mocking getters and setters

How to mock getter-setter method in the below implementation?

MyClass obj=new MyClass();

obj.getName().setFirstName("hello"); // How to Mock this part ? 

Testing

@Mock
MyClass obj;

@Test
void testing(){

  doNothing().when(obj).getName().setName(anyString()); //this doesn't work

}

Upvotes: 1

Views: 3924

Answers (3)

Gray
Gray

Reputation: 116858

The problem here is that there are two objects involved: your mocked MyClass and the object returned by getName(). You need to mock both of them.

@Mock
MyClass obj = new MyClass();
@Mock
MyName name = new MyName();
...
when(obj).getName().theReturn(name);
when(name).setName(anyString());

This allows you to define the behavior of both objects separately. See @Yassin's answer if you want to use Mokito.RETURNS_DEEP_STUBS feature which mocks the complete call chain.

Obviously if you are trying to test whether or not a class set/get work and return the right stuff should be done on a concrete instance of the class and not on a mock object.

Upvotes: 0

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

What you need is to add the flag RETURNS_DEEP_STUBS to your mock.

// if your mock is instantiated with the annotation
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
MyClass obj;

// if your mock is instantiated with the factory method
MyClass obj = Mockito.mock(MyClass.class, Answers.RETURNS_DEEP_STUBS)

Upvotes: 1

Akif Hadziabdic
Akif Hadziabdic

Reputation: 2890

You do not need to set a value, just define the value which will getter return.

when(obj.getName()).thenReturn("hello");

Upvotes: 0

Related Questions