Mockito is a framework in Java that creates Test Doubles for users that can be used with Junit. Test Doubles as described in my last blog are basically simplified tests for your code that more or less test setup over functionality. They are used to help you make sure you are setting up your code correctly in the early stages before it gets overly complicated. It’s good practice to test at this early stage in the process because simple setup and organization errors can become an overwhelming problem further down the line if you don’t find them early on. Mockito is a great framework to help you quickly generate these Test Doubles. Mockito creates mock objects with dummy values to make sure tests pass, as long as your setup is correct.
Check out this code example:
package com.journaldev.mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import com.journaldev.AddService;
import com.journaldev.CalcService;
public class CalcService1Test {
@Test
void testCalc() {
System.out.println(“**— Test testCalc executed —**”);
AddService addService;
CalcService calcService;
addService = Mockito.mock(AddService.class);
calcService = new CalcService(addService);
int num1 = 11;
int num2 = 12;
int expected = 23;
when(addService.add(num1, num2)).thenReturn(expected);
int actual = calcService.calc(num1, num2);
assertEquals(expected, actual);
}
}
This code uses a mock() method.
To continue reading about this example check out this website:
https://www.journaldev.com/21816/mockito-tutorial
From the blog cs@worcester – Zac's Blog by zloureiro and used with permission of the author. All other rights reserved by the author.