【发布时间】:2021-05-21 12:32:23
【问题描述】:
下面是我使用 RestTemplate 的 EmployeeService,我为此编写了正在工作的 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);
}
}
【问题讨论】:
-
我认为问题是你正在初始化服务实体,试试@InjectMocks private EmployeeService empService;;
-
它仍然进行实际调用。我刚刚修改了我的 EmployeeService 代码。我没有自动装配 RestTemplate 对象
-
删除
new EmployeeService。此外,您不应该创建一个新的RestTemplate,而是在您的服务中使用 Spring 注入它(使用@Bean方法中的RestTemplateBuilder创建一个)。 -
@M.Deinum 解决方案正在运行。谢谢
标签: spring spring-boot junit mocking spring-boot-test