下面是我的employeeservice使用resttemplate,我已经为它编写了junit,它正在工作。但问题是我的junit正在实际调用rest端点。如何避免实际调用rest?
@Service
public class EmployeeService {
private RestTemplate restTemplate = new RestTemplate();
public Employee getEmployee(String id) {
ResponseEntity resp =
restTemplate.getForEntity("http://localhost:8080/employee/" + id, Employee.class);
return resp.getStatusCode() == HttpStatus.OK ? resp.getBody() : null;
}
}
@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);**// Actual call happens .How to avoid it.**
Assert.assertEquals(emp, employee);
}
}
2条答案
按热度按时间k3bvogb11#
您正在创建一个显式的新restemplate();
所以,你不能嘲笑它。
一种方法是创建一个执行实际调用的@component。
所以,你从课堂上说
在测试中,您模拟了新类,并在它:
pdtvr36n2#
你需要把测试改成模拟
通过做