我有一个REST请求服务,可以将GET请求发送到外部API。该课程如下。每当我尝试运行测试以检查请求是否成功时,都会出现以下错误:
预期进一步的请求,剩下1个未满足的预期。已执行0个请求
任何人都知道发生了什么事或如何改进此测试?
@Slf4j
@Service
public class APIrequestService {
@Autowired
RestTemplate restTemplate;
@Async
public String request(int id, String url, String endpoint) {
String fullUrl = url + endpoint;
log.debug(fullUrl);
String idVar = Integer.toString(id);
log.debug("Studentid");
try{
return restTemplate.getForObject(fullUrl, String.class, idVar);
}
catch (HttpClientErrorException | HttpServerErrorException httpClientOrServerExc) {
if (HttpStatus.NOT_FOUND.equals(httpClientOrServerExc.getStatusCode())) {
return "Student not found in system";
}
return "Not known error";
}
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder.build();
}
}
我的测试是以下课程:
RunWith(SpringRunner.class)
public class APIRequestServiceTest {
@TestConfiguration
static class RequestServiceContextConfiguration {
@Bean
@Qualifier("TestService")
public APIrequestService apiRequestService() {
return new APIrequestService();
}
}
@Qualifier("TestService")
@Autowired
APIrequestService apIrequestService;
@MockBean
private RestTemplate restTemplate;
private MockRestServiceServer mockRestServiceServer;
@Before
public void setUp() {
RestGatewaySupport gatewaySupport = new RestGatewaySupport();
gatewaySupport.setRestTemplate(restTemplate);
mockRestServiceServer = MockRestServiceServer.createServer(gatewaySupport);
}
@Test
public void testGetResponseWhenRequest() {
mockRestServiceServer.expect(once(), requestTo("https://my-json-server.typicode.com/tijn167/fakejsonapi/student/2102241"))
.andRespond(withSuccess("", MediaType.APPLICATION_JSON));
String result = apIrequestService.request(2102241, "https://my-json-server.typicode.com/tijn167/fakejsonapi", "/student" );
System.out.println(result);
mockRestServiceServer.verify();
assertEquals("{student: 210221}", result);
}