Config Mock (Unit Test past 2)

Tram Ho

1. when and thenReturn

Mock can return different values ​​depending on the parameters you pass in the method. When and Then Return are a sequence of methods used to specify the return value for a method call with pre-defined parameters.

Example

The When and ThenReturn method string may return an exeption
Example

2. “doReturn When” and “doThrow When”

doReturn () .. When () is similar to when () .. thenReturn (). It is very useful in creating mock methods to create exceptions during the Example test

doThrow is used to return an exeption.
Example

3. Wrapping a Java object with Spy

@Spy or spy () method can be used to wrap a real object.
Example

4. Veryfy the call on the mock object

Mockito keeps track of all method calls and parameters of a Mock object. Use verify () on Mock objects to verify that the specified conditions have been met.
example

5. Use @InjectMock to create dependencies via Mockito

Annotation @InjectMock implements constructors, methods, and fields depending on its type
example

The above class is constructed via Mockito and its dependencies are expressed by Mock example objects

Mockito can inject an object by Inject constructor, setter or properties.

6. References

https://www.vogella.com/tutorials/Mockito/article.html

Share the news now

Source : Viblo