Search code examples
javaspring-bootjunitmockito

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

}

Solution

  • 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.