Mockito’s mock Methods

By | October 15, 2020

In this post, We will talk and learn about different overloaded mock() methods of org.mockito.Mockito class

Mockito’s class org.mockito.Mockito provides below overloaded mock Methods:

public static <T> T mock(Class<T> classToMock): It creates mock object of given class or interface.

public static <T> T mock(Class<T> classToMock, String name) : In this method we can specify mock name. mock name can be helpful for debugging in all verification errors.

public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) : This method creates mock with a specified strategy for its answers to interactions. It’s quite an advanced feature and typically we don’t need it to write general tests. However, it can be helpful when we work with legacy systems.

public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) :  This method creates a mock with some non-standard settings.The number of configuration points for a mock grows so we need a fluent way to use new configuration without adding lot of overloaded Mockito.mock() methods.

Let’s try to understand the above concept using a demo project:

pom.xml

 

MyList.java

MyCustomAnswer.java

 

MockitoMocksTest,java

 

The Output of the above project:

You May Also Like:

What is Mocking?
Why Need for mocking?
What are the Benefits of Mockito?
How to mock interface using Mockito example?
Mockito and JUnit Integration Using Maven Example
@Mock and @Spy Mockito Annotations With Example
@InjectMocks Annotation in Mockito with Example
Mockito – Verifying Method Calls
@Captor Annotation in Mockito with Example
Adding behavior to mocked object in Mockito
Mocking Void Methods with Mockito
Mocking Exception Throwing using Mockito

That’s all about Mockito’s mock Methods
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *