Useful Mockito withSettings() Methods For Testing
In one of our previous articles How to Mock Variables for Interfaces and Casts in Java we described how to use the method
withSettings().extraInterfaces() in order to add more interfaces / implementations to mocked objects. In this article we’ll look at other similar methods.
The withSettings() method in Mockito provides several useful methods that can be used to customize the behavior of mock objects. Here are some examples of the methods provided by withSettings():
- name(): This method is used to give a name to the mock object. The name can be useful when debugging or logging test failures.
- defaultAnswer(): This method is used to specify a default answer for the mock object. The default answer is used when no explicit behavior is defined for a method call on the mock object.
- serializable(): This method is used to create a mock object that can be serialized.
- verboseLogging(): This method is used to enable verbose logging for the mock object. This can be useful when debugging test failures.
- stubOnly(): This method is used to create a mock object that only allows stubbing and doesn’t allow method calls that aren’t stubbed.
Here’s an example of how these methods can be used with withSettings():
// Create a mock object with custom settings List<String> mockList = mock(List.class, withSettings() .name("mockList") .defaultAnswer(RETURNS_SMART_NULLS) .serializable() .verboseLogging() .stubOnly()); // Set up behavior for the mock object when(mockList.get(0)).thenReturn("first"); // Call the method under test String result = mockList.get(0); // Verify that the mock object behaves as expected assertEquals("first", result);
In the above example, we create a mock object for the List interface with custom settings. We give the mock object a name, specify a default answer of RETURNS_SMART_NULLS, make it serializable, enable verbose logging, and make it stubOnly. We then use the when() method to set up the behavior for the get() method, and call it to obtain the result. Finally, we use assertions to verify that the mock object behaves as expected.
Overall, withSettings() is a powerful method that can be used to create mock objects with custom behavior and characteristics. It is particularly useful when you need to create complex mock objects that require specific settings or behavior.
CommentsSo empty here ... leave a comment!