避免在 RestTemplate Junit 中进行实际的 Rest 调用

Avoid making actual Rest call in RestTemplate Junit

下面是我的 EmployeeService 使用 RestTemplate,我已经为其编写了 Junit,它正在工作。但问题是我的 JUNIT 正在对 Rest end 进行实际调用 point.How 我可以避免进行实际的 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);
}
}

因此,您从 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);
...
    }
}

从测试中你模拟了新的 class 并且当它:

@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