• Home
  • junit 5 and mockito mocking getters and setters java

junit 5 and mockito mocking getters and setters java

To mock a getter or setter method using Mockito, you can use the when and 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 doNothing method:

doNothing().when(myObject).setName("John");

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.