Author

Author- Ram Ranjeet Kumar
Showing posts with label Mockito. Show all posts
Showing posts with label Mockito. Show all posts

Saturday, August 19, 2023

Mockito Mock Method

 


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.

Mockito is a popular Java library used for unit testing. It allows you to create mock objects to simulate the behavior of real objects and isolate the code you're testing from external dependencies. One of the key features of Mockito is its ability to mock methods, enabling you to define the behavior of mocked methods and verify their interactions.

Here's an explanation and an example of how to use Mockito to mock methods:

1. Creating Mock Objects:

In Mockito, you can create mock objects using the `Mockito.mock()` method.  This method generates a mock instance of the specified class or interface. The mock object behaves as if it were a real instance of the class, but you can define its behavior, such as what methods should return or how they should behave when called.


2. Stubbing Method Behavior:

Mocking a method involves defining what it should return when it's called. This is done using the `when().thenReturn()` syntax. You tell Mockito what method to mock and what value to return when that method is called on the mock object.


3. Verifying Method Calls:

After you've defined the behavior of the mock methods and have used them in your code, you can verify if specific methods were called with the expected arguments. This is done using the `verify()` method in Mockito.

Example:

Suppose you have a `Calculator` class that you want to test. This calculator uses an external `MathService` to perform calculations. Here's how you would use Mockito to mock the `MathService` and test the `Calculator`:


import org.junit.jupiter.api.Test;

import org.mockito.Mockito;

import static org.junit.jupiter.api.Assertions.assertEquals;

import static org.mockito.Mockito.verify;

import static org.mockito.Mockito.when;

public class CalculatorTest {

   @Test

    public void testAdd() {

        // Create a mock MathService

        MathService mathService = Mockito.mock(MathService.class);

        // Stub the behavior of the add method

        when(mathService.add(2, 3)).thenReturn(5);

        // Create a Calculator instance using the mock MathService

        Calculator calculator = new Calculator(mathService);

         // Perform the test

        int result = calculator.add(2, 3);

        // Verify that the mathService.add method was called with the expected arguments

        verify(mathService).add(2, 3);

        // Verify the result

        assertEquals(5, result);

    }

}


In this example, the `MathService` is mocked using `Mockito.mock()`, and its `add` method behavior is defined using `when().thenReturn()`. The test then creates a `Calculator` instance using the mock `MathService`. After performing the calculation, the `verify()` method checks whether the `add` method of the mock was called with the expected arguments.

This example demonstrates how to mock a method's behavior and verify its usage during unit testing using Mockito.

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.

Wednesday, August 16, 2023

Mockito Framework


Introduction
  • Mockito is an open-source testing framework for Java released under the MIT(Massachusetts Institute of Technology)  License. 
  • Mockito is a Java-based mocking framework used for unit testing of Java applications. 
  • Mockito plays a crucial role in developing testable applications.
  • Mockito is a testing technique where mock objects are used instead of real objects for testing purposes. 
  • Mock objects provide a specific (dummy) output for a particular (dummy) input passed to it.

Here's a simple explanation with an example:
Imagine you're building a car. Your car has an engine, and the engine needs to be tested. But, testing the engine might involve other complex parts like the transmission and fuel system. Instead of building an entire car just to test the engine, you could use a mock engine that simulates the real engine's behavior.

In coding terms, Mockito lets you create these "mock" objects to stand in for real components. You can use these mock objects to check if certain interactions between parts of your code are happening correctly.

Let's say you have a class called `Car` that depends on an `Engine` class. You want to test the `Car` class without worrying about the `Engine` class's actual behavior. Here's how you could do it with Mockito:

import static org.mockito.Mockito.*;
// Imagine you have these classes
class Engine {
    public String start() {
        return "Vroom!";
    }
}

class Car {
    private Engine engine;

    public Car(Engine engine) {
        this.engine = engine;
    }

    public String startCar() {
        return engine.start();
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a mock engine
        Engine mockEngine = mock(Engine.class);

        // Set up the mock's behavior
        when(mockEngine.start()).thenReturn("Mock Vroom!");

        // Create a car using the mock engine
        Car car = new Car(mockEngine);

        // Test the car's behavior
        String carStartSound = car.startCar();
        System.out.println(carStartSound); // Output: "Mock Vroom!"
    }
}

In this example, `mock(Engine.class)` creates a mock object that behaves like an `Engine` but doesn't have the real engine's functionality. The `when(mockEngine.start()).thenReturn("Mock Vroom!")` line sets up the mock engine to return `"Mock Vroom!"` when its `start()` method is called.

By using Mockito, you can test the `Car` class's behavior without relying on the real `Engine` class, making your tests faster, more focused, and easier to maintain.


What is the difference between Mockito and JUnit?
  • JUnit and Mockito are widely used testing frameworks in the Java ecosystem, each serving distinct purposes. 
  • JUnit is a unit testing framework that focuses on writing and executing test cases for individual units of code. 
  • Mockito, on the other hand, is a mocking framework specifically designed to create mock objects for testing purposes. 
  • While JUnit focuses on testing individual units of code, Mockito specializes in managing dependencies and mocking external interactions.
  • In summary, JUnit and Mockito are two powerful and complementary testing frameworks for Java applications.

Benefits of Mockito
Mockito is a popular Java mocking framework that allows you to create mock objects for unit testing. Some of the benefits of Mockito include:
  • No handwriting: In Mockito, there is no requirement for writing your mock objects.
  • Safe refactoring: While renaming the method name of an interface or reordering parameters will not break the test code as Mocks are created at run time.
  •  Annotation support: It supports creating mocks using various annotations.
  •  Return value support: Supports return values.
  •  Exception support: It supports exceptions.