Show List

Writing unit tests with Mockito

Unit testing is a software testing technique that involves testing individual units or components of code in isolation to ensure that they work as expected. Mockito is a popular Java mocking framework used to write unit tests. It allows you to create mock objects that simulate the behavior of real objects, which makes it easier to test your code.

Here's an example of how to write unit tests with Mockito:

Let's say you have a simple class called "Calculator" that performs basic arithmetic operations. Here's the code:

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

To test this class using Mockito, you would need to do the following:

  • Create a mock object of the Calculator class using the Mockito framework. This will allow you to simulate the behavior of the actual Calculator class.
python
Copy code
Calculator calculator = Mockito.mock(Calculator.class);
  • Define the behavior of the mock object using Mockito's when() method. In this case, we want to specify that when the add() method is called with the arguments 2 and 3, it should return 5.
csharp
Copy code
Mockito.when(calculator.add(2, 3)).thenReturn(5);
  • Call the method(s) you want to test and assert the expected results. In this case, we want to test the add() method.
scss
Copy code
int result = calculator.add(2, 3); assertEquals(5, result);

Here's the full example:

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

This example demonstrates the basic steps involved in writing unit tests with Mockito. By creating mock objects and defining their behavior, you can easily test your code in isolation and ensure that it works as expected.


    Leave a Comment


  • captcha text