我分别有Spring Boot控制器和logger服务方法,通过发送请求调用控制器时,logger服务必须收集有关请求和响应的数据,并通过restemplate将其发送到外部logger服务。我想配置或找到在micorservice环境中的单元测试中使用Restemplate的解决方案
当我尝试通过邮递员向控制器发送请求时,控制器方法运行良好。它按预期运行。但是当我测试控制器本身时,restemplate的postForObject(...)方法始终返回null值。但是,这对于控制器方法是不正常的。 控制器方法名称:findAllCrmDevices() 服务方法名称:log(日志日志)-如下所示
@RequestMapping(value = "/find-all-crm-devices", method = RequestMethod.GET)
public ResponseEntity<RestApiObject> findAllCrmDevices(){
logger.info("device_controller.find_all_devices --> pre start");
Logs logs = new Logs();
RestApiObject restApiObject = new RestApiObject();
try {
logs.setRequestBody("{}");
List<DeviceDetails> devices = iDeviceService.findAll();
restApiObject.setObject(devices);
restApiObject.setCode(environment.getProperty("ok",Integer.class));
restApiObject.setMessage(environment.getProperty("message_0"));
restApiObject.setHostAddress(NetUtility.getLanAddress());
logs.setResponseBody(objectMapper.writeValueAsString(restApiObject));
logs.setResponseDate(new Date());
loggerService.log(logs);
} catch (RestLoggingException e){
logger.error("Error",e);
restApiObject.setCode(e.getCode());
restApiObject.setMessage(e.getMessage());
} catch (Exception e) {
logger.error("Error",e);
restApiObject.setCode(environment.getProperty("ex9999",Integer.class));
restApiObject.setMessage(environment.getProperty("message_9999"));
}finally {
return new ResponseEntity<>(restApiObject,HttpStatus.OK);
}
}
@Override
public void log(Logs logs) throws RestLoggingException {
logger.info("logger_service_impl.log() --> log: {}",logs);
RestApiObject response = restTemplate.postForObject(saveLogUrl,logs, RestApiObject.class);
logger.info("logger_service_impl.log() --> log service url: {}",saveLogUrl);
logger.info("logger_service_impl.log() --> rest api object: {}",response);
if (response.getCode() == 9999){
logger.info("logger_service_impl.log() --> failed to log");
throw new RestLoggingException(environment.getProperty("message_9001"),
environment.getProperty("ex9001",Integer.class));
}
logger.info("logger_service_impl.log() --> successfully logged");
}
@Test
public void findAllCrmDevicesTest() throws Exception{
mvc.perform(
get("/api/device/find-all-crm-devices").
contentType(MediaType.APPLICATION_JSON_UTF8)
)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.code",is(0)))
.andExpect(jsonPath("$.object",allOf(notNullValue(),not(emptyArray()))));
// TODO: 8/20/2019
}