java - Spring Boot - 模拟对外部 API 的 POST REST 请求
问题描述
我有一个 Spring-Boot 1.5.21 应用程序,它充当 Angular UI 和提供数据的外部 API 之间的 REST 网关(长篇大论——充当 UI 和数据源之间的身份验证)。一个请求来到 Spring-Boot 应用程序,它使用请求负载调用数据源 API。
我是 Spring-Boot 单元测试的新手,我正在尝试为网关应用程序中的 POST REST 方法编写测试,以创建新记录(创建)。我已经阅读了一些教程和其他网站,详细介绍了如何对 Spring-Boot API 进行单元测试,但对我的情况没有任何帮助。
我想要:
- 单元测试 REST Controller 方法并检查 @RequestBody 是否有效
- 我不想在数据源中创建记录
控制器方法:
@PostMapping(value = "/" + Constants.API_CHANGE_REQUEST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String submitChangeRequest(@RequestBody ChangeRequestWrapper changeRequestWrapper) {
logger.info("API Request: Posting Change Request: " + changeRequestWrapper.toString());
return restService.makeApiPost(sharedDataService.buildApiUrlPath(Constants.API_CHANGE_REQUEST), changeRequestWrapper);
}
应用配置:
@PropertySource({"classpath:application.properties"})
@Configuration
public class AppConfig {
@Resource
private Environment env;
@Bean
public RestTemplate restTemplate() {
RestTemplateBuilder builder = new RestTemplateBuilder();
return builder
.setConnectTimeout(Constants.API_TIMEOUT_CONNECT)
.setReadTimeout(Constants.API_TIMEOUT_READ)
.basicAuthorization(env.getProperty("bpm.user"), env.getProperty("bpm.password"))
.build();
}
}
RestServiceImpl:
@Service
public class RestServiceImpl implements RestService {
private static final Logger logger = LoggerFactory.getLogger(RestServiceImpl.class);
@Autowired
private RestTemplate myRestTemplate;
@Value("${bpm.url}")
private String restUrl;
public String getApiUri() {
return restUrl;
}
public String makeApiCall(String payload) /*throws GradeAdminException */{
logger.info("Implementing API call.");
logger.debug("userApi: " + payload);
return myRestTemplate.getForObject(payload, String.class);
}
public String makeApiPost(String endpoint, Object object) {
logger.info("Implementing API post submission");
logger.debug("userApi endpoint: " + endpoint);
return myRestTemplate.postForObject(endpoint, object, String.class);
}
}
SharedDataServiceImpl:
@Service
public class SharedDataServiceImpl implements SharedDataService {
@Autowired
private RestService restService;
@Override
public String buildApiUrlPath(String request) {
return buildApiUrlPath(request, null);
}
@Override
public String buildApiUrlPath(String request, Object parameter) {
String path;
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(restService.getApiUri());
if (parameter != null) {
builder = builder.path(getApiPath(request) + "/{object}");
UriComponents buildPath = builder.buildAndExpand(parameter);
path = buildPath.toUriString();
} else {
builder = builder.path(getApiPath(request));
path = builder.build().toUriString();
}
return path;
}
}
我为 GET 方法做了什么:
@RunWith(SpringRunner.class)
@WebMvcTest(ClientDataRequestController.class)
@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigWebContextLoader.class)
public class ClientDataRequestControllerTest {
@Autowired
private MockMvc mvc;
@Before
public void setUp() {
}
@Test
public void test_no_endpoint() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isNotFound()).andReturn();
}
@Test
public void test_controller_no_endpoint() throws Exception {
this.mvc.perform(get("/api/")).andExpect(status().isOk()).andReturn();
}
@Test
public void test_getStudent_valid_parameters() throws Exception {
this.mvc.perform(get("/api/students/?pidm=272746")).andExpect(status().isOk()).andReturn();
}
}
我将非常感谢一些帮助。
解决方案:
从那以后,我发现这个 SO answer解决了我的问题。
解决方案
您可以模拟 RestServiceImpl。在您的测试中添加一个依赖项并使用 MockBean 对其进行注释:
@MockBean
private RemoteService remoteService;
现在您可以继续模拟这些方法:
import org.mockito.BDDMockito;
BDDMockito.given(this.remoteService.makeApiPost()).willReturn("whatever is needed for your test");
推荐阅读
- mysql - zabbix trigger for 2个字段的2个值之间的差异
- spring - 使用 AsyncItemProcessor 和 AsyncItemWriter 时数据库连接超时
- python - 对象在没有 session.commit() 的情况下添加到数据库
- google-chrome - 强制 Chrome Inspector 显示真实的源代码而不是它的解释
- php - PHP 上是否有保证的文件资源?
- javascript - 如何装饰 Web 组件类
- node.js - 使用 VSTS 在 Azure Web 应用程序上部署 Node.js 应用程序。成功部署后,应用程序代码文件在 Web 应用程序目录结构中不可用
- python - 如何使用解密密钥加密和解密熊猫数据帧?
- r - (在 R 中)将元数据从向量添加到数据帧的一组列?
- c++ - C ++将未知数量的整数读取到cin并输出总和