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 ? 


MyClass obj;

void testing(){

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



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.

MyClass obj = new MyClass();
MyName name = new MyName();

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.