Author

Author- Ram Ranjeet Kumar

Saturday, August 19, 2023

Methods of Mockito



Mockito is a popular Java library that provides tools for creating mock objects in unit tests. These mock objects can simulate the behavior of real objects, allowing you to isolate and test specific parts of your code without relying on actual dependencies. Mockito provides a variety of methods to set up and verify interactions with mock objects. Here are some commonly used Mockito methods:

1.mock(): This method is used to create a mock object of a given class or interface. It returns an instance of the specified type with all methods stubbed out.

   SomeClass mockObject = Mockito.mock(SomeClass.class);


2. when(): This method is used to set up expectations for method calls on mock objects. You can define return values or exceptions to be thrown when specific methods are called.

   

   when(mockObject.someMethod()).thenReturn(someValue);

   when(mockObject.anotherMethod()).thenThrow(SomeException.class);

  

3. verify(): This method is used to verify that specific methods were called on a mock object during the test. You can specify the expected number of invocations and whether the methods were called in a specific order.

   verify(mockObject).someMethod();

   verify(mockObject, times(2)).anotherMethod();

   

4. any() and eq(): These methods are used as argument matchers in `when()` and `verify()` statements. `any()` matches any value of the corresponding parameter type, while `eq()` matches a specific value.


   when(mockObject.someMethod(any(String.class))).thenReturn(someValue);

   verify(mockObject).anotherMethod(eq(42));


5. doReturn(), doThrow(), doAnswer(), doNothing(), and doCallRealMethod(): These methods are used to define stubbing behaviors when dealing with methods that return void, throw exceptions, or require custom behavior.


   doThrow(new SomeException()).when(mockObject).someMethod();

   doAnswer(invocation -> "Custom Response").when(mockObject).anotherMethod();


6. spy(): This method is used to create a partial mock of a real object. It allows you to retain the original behavior of certain methods while stubbing out others.


   RealObject realObject = new RealObject();

   RealObject spyObject = Mockito.spy(realObject);

   

7. reset(): This method is used to reset the state of a mock object. It clears all interactions and stubbing.

   Mockito.reset(mockObject);


These are just a few of the many methods provided by the Mockito framework. Mockito's documentation and resources provide more information on how to effectively use these methods to write meaningful and effective unit tests.

No comments:

Post a Comment