Show List

Creating mock objects with Mockito

Creating mock objects with Mockito is a straightforward process. The following are the steps to create a mock object with Mockito:

  • Import the necessary Mockito classes:
java
Copy code
import static org.mockito.Mockito.*;
  • Create the mock object:
java
Copy code
MyClass myMock = mock(MyClass.class);

In this example, we are creating a mock object of the MyClass class. The mock() method is a static method in the Mockito class that creates a mock object of the specified class.

  • Configure the mock object:
java
Copy code
when(myMock.myMethod()).thenReturn("hello world");

In this example, we are configuring the mock object to return the string "hello world" when the myMethod() method is called.

  • Use the mock object in a test:
java
Copy code
String result = myMock.myMethod(); assertEquals("hello world", result);

In this example, we are calling the myMethod() method on the mock object and storing the result in a string variable. We then use the assertEquals() method to verify that the result is equal to the string "hello world".

Here is a complete example that demonstrates how to create and use a mock object with Mockito:

java
Copy code
import static org.mockito.Mockito.*; public class MyClassTest { @Test public void testMyMethod() { // Step 1: Create the mock object MyClass myMock = mock(MyClass.class); // Step 2: Configure the mock object when(myMock.myMethod()).thenReturn("hello world"); // Step 3: Use the mock object in a test String result = myMock.myMethod(); assertEquals("hello world", result); } }

This is just a basic example of how to create and use a mock object with Mockito. There are many more features available in Mockito, such as argument matching, verifying method calls, and more.


    Leave a Comment


  • captcha text