spring boot junit 5 mockito service class test code example

Example 1: mockito test for resttemplate

@RunWith(MockitoJUnitRunner.class)
public class EmployeeServiceTest {
 
    @Mock
    private RestTemplate restTemplate;
 
    @InjectMocks
    private EmployeeService empService = new EmployeeService();
 
    @Test
    public void givenMockingIsDoneByMockito_whenGetIsCalled_shouldReturnMockedObject() {
        Employee emp = new Employee(“E001”, "Eric Simmons");
        Mockito
          .when(restTemplate.getForEntity(
            “http://localhost:8080/employee/E001”, Employee.class))
          .thenReturn(new ResponseEntity(emp, HttpStatus.OK));
 
        Employee employee = empService.getEmployee(id);
        Assert.assertEquals(emp, employee);
    }
}

Example 2: mockito mock resultset

Mockito.when(resultSetMock.next()).thenReturn(true).thenReturn(false);

Tags:

Misc Example