Show List

Using Mockito with JUnit and other testing frameworks

Mockito is a popular mocking framework that can be used with different testing frameworks like JUnit, TestNG, and Spock. Mockito provides a set of APIs that can be used to create mock objects, stub methods, and verify method calls.

Here's an example of how to use Mockito with JUnit:

Suppose you have a class called "Calculator" that performs some basic arithmetic operations. You want to test the "add" method of this class using Mockito with JUnit.

java
Copy code
public class Calculator { public int add(int a, int b) { return a + b; } }

To test the "add" method with Mockito and JUnit, you would need to do the following:

  • Create a test method that uses the JUnit @Test annotation.
typescript
Copy code
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import org.junit.Test; public class CalculatorTest { @Test public void testAdd() { // test code goes here } }
  • Create a mock object of the Calculator class using the Mockito.mock() method.
scss
Copy code
Calculator calculator = mock(Calculator.class);
  • Stub the "add" method of the Calculator class to return a specific value using the Mockito.when() method.
less
Copy code
when(calculator.add(2, 3)).thenReturn(5);
  • Call the "add" method of the Calculator class using the mock object and verify that it returns the expected value.
scss
Copy code
int result = calculator.add(2, 3); assertEquals(5, result);
  • Verify that the "add" method of the Calculator class was called with the expected arguments using the Mockito.verify() method.
scss
Copy code
verify(calculator).add(2, 3);

Here's the full example:

scss
Copy code
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import org.junit.Test; public class CalculatorTest { @Test public void testAdd() { Calculator calculator = mock(Calculator.class); when(calculator.add(2, 3)).thenReturn(5); int result = calculator.add(2, 3); assertEquals(5, result); verify(calculator).add(2, 3); } }

This example demonstrates how to use Mockito with JUnit to test a method of a class. By using the Mockito.mock() method to create a mock object and the Mockito.when() method to stub the method, you can isolate the method under test and verify its behavior. By using the Mockito.verify() method, you can verify that the method was called with the expected arguments. This approach can be applied to other testing frameworks as well, by using the appropriate annotations and syntax.


    Leave a Comment


  • captcha text