To mock a getter or setter method using Mockito, you can use the
thenReturn methods. For example:
MyClass myObject = mock(MyClass.class); when(myObject.getName()).thenReturn("John");
This will set up a mock object for
myObject, and when the
getName method is called on it, it will return the string “John”.
To mock a setter method, you can use the
This will set up the mock object to do nothing when the
setName method is called with the argument “John”.
It’s important to note that mocking getters and setters is generally considered a bad practice, as it can lead to fragile and hard-to-maintain tests. It’s usually better to mock the actual business logic of a class rather than its getters and setters.