问题描述
下面是我的 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);
}
}
解决方法
您正在创建一个显式的 new RestTemplate();
所以,你不能嘲笑它。
一种方法是创建一个执行实际调用的@Component。
@Component
public class MyHttpClient {
public ResponseEntity callingMethod(RestTemplate restTemplate,String id) {
restTemplate.getForEntity("http://localhost:8080/employee/" + id,Employee.class);
}
}
所以,你从类中调用它
@Service
public class EmployeeService {
@Autowired
private myHttpClient MyHttpClient;
private RestTemplate restTemplate = new RestTemplate();
public Employee getEmployee(String id) {
ResponseEntity resp = myHttpClient.callingMethod(restTemplate,id);
...
}
}
在测试中你模拟了新课程和你:
@Mock
private MyHttpClientMock myHttpClientMock;
when(myHttpClientMock.callingMethod(Mockito.<RestTemplate> any()).thenReturn(HttpStatus.OK);
,
您需要将测试更改为模拟
public Employee getEmployee(String id)
做事
doReturn(emp).when(empService).getEmployee(1);//or a wild card