This post shows how to mock a method that returns unique values for different arguments in Mockito. For example, the return values vary according to the method argument. Sample Codes To Mock Suppose we have the following Java classes. The
Should you use Mockito thenReturn or thenAnswer?
Should you use Mockito thenReturn or thenAnswer? It depends! The thenReturn returns the same value in every method run; while the thenAnswer does not. We use the former to return hard-coded values; while we use the latter for derived values.
Mock methods that return void
Previously, I posted Void methods and Mockito in Java that verifies if any of the methods of a object passed as a argument were invoked. This time we want to alter the behavior of a method that returns void.
Void methods and Mockito in Java
When we talk about unit tests, we think about input values and return values to/from methods. Returned values are checked against expected values as a way to verify behavior of codes. But how would you test codes that do not return any values? Essentially, we resort to stubbing out void methods. That is easy in Mockito!
Capture Argument To Method in Mockito
This post shows how to capture arguments our codes passed to a mock’s method. To do this, a method must accept reference types. Then, we use Mockito.verify() method. Then, pass an instance of ArgumentCaptor to the mock’s method. Capture Argument
Find out if an object is a mock or spy in Mockito
The need for it [wp_ad_camp_5] Finding out if an object is a mock or spy in Mockito may not (or never) be part of your usual automated unit tests but in some cases (advanced usage of JUnit/Mockito) you may need
Mockito Spy
Spy Objects [wp_ad_camp_5] A Mockito spy allows us to create a spy object from a real object with similar behavior where each method can be stubbed out when needed. It is ideal for testing legacy code as you cannot invoke
Three ways to mock an object using Mockito
If you’re new to Mockito and have only seen a sample or two on the Internet, you might find other examples create mock objects in different ways using the same framework. As a matter of fact, there are three (3) ways to create mock objects in Mockito.
Using Mockito @InjectMocks with Constructor and Field Injections
There is a scenario to watch out for where we have class with a few instance variables of reference types but not all of them get initialized via a constructor. This post demonstrates shows how we could unknowingly miss initializing other mocks in a class and how to fix them.