resttemplate dummy endpoint for unit testing code example

Example: 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);
    }
}

Tags:

Misc Example