避免在rest模板junit中进行实际的rest调用

dfuffjeb  于 2021-07-23  发布在  Java
关注(0)|答案(2)|浏览(344)

下面是我的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);
    }
}
k3bvogb1

k3bvogb11#

您正在创建一个显式的新restemplate();
所以,你不能嘲笑它。
一种方法是创建一个执行实际调用的@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);
pdtvr36n

pdtvr36n2#

你需要把测试改成模拟

public Employee getEmployee(String id)

通过做

doReturn(emp).when(empService).getEmployee(1);//or a wild card

相关问题