gpt4 book ai didi

java - Spring Boot - 模拟对外部 API 的 POST REST 请求

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:00 24 4
gpt4 key购买 nike

我有一个 Spring-Boot 1.5.21 应用程序,它充当 Angular UI 和提供数据的外部 API 之间的 REST 网关(长话短说 - 充当 UI 和数据源之间的身份验证)。请求到达 Spring-Boot 应用程序,它使用请求负载调用数据源 API。

我是 Spring-Boot 单元测试的新手,正在尝试为创建新记录(创建)的网关应用程序中的 POST REST 方法编写测试。我读过一些教程和其他网站,详细介绍了如何对 Spring-Boot API 进行单元测试,但对我的情况没有任何帮助。

我想要:

  • 对 REST Controller 方法进行单元测试并检查 @RequestBody 是否有效
  • 我不想在数据源中创建记录

Controller 方法:

@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();
}
}

我非常感谢您在这方面的帮助。

解决方案:

我已经找到了this SO answer这解决了我的问题。

最佳答案

您可以模拟 RestServiceImpl。在测试中添加依赖项并使用 MockBean 对其进行注释:

@MockBean
private RemoteService remoteService;

现在您可以继续模拟这些方法:

import org.mockito.BDDMockito;


BDDMockito.given(this.remoteService.makeApiPost()).willReturn("whatever is needed for your test");

关于java - Spring Boot - 模拟对外部 API 的 POST REST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56738006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com