java - 让我的 @Test GET 请求在 Spring Boot 中工作
问题描述
初学者在这里。我使用 java 在 Spring Boot 中创建了一个 API,我想测试 GET 请求是否返回 200。我对检查返回的内容(JSON 对象)不感兴趣,我只想检查此连接是否有效。到目前为止,我已经尝试过这段代码:
@Test
void getRequest() throws Exception {
// this doesn't work because a ResultMatcher is needed
this.mvc.perform(get("/currencies")).andExpect(HttpStatus.ACCEPTED);
//tried this too and I get "Cannot resolve method 'assertThat(int, int)'"
RequestBuilder request = get("/currencies");
MvcResult result = mvc.perform(request).andReturn();
assertThat(result.getResponse().getStatus(), 200);
}
在第一个声明中,我的字面意思是“对此基本 url 执行获取请求并期望 http 接受状态”它不喜欢它。我要求太多了吗?
我的第二次尝试是“创建一个 MvcResult 对象并将 GET 请求的结果存储在其中。然后将其与状态代码 200 进行比较”
这是完整的课程
import com.example.CoinAPI.controller.CoinController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@AutoConfigureMockMvc
@SpringBootTest
class CoinApiApplicationTests {
@Autowired
private CoinController controller;
@Autowired
private MockMvc mvc;
@Test
void contextLoads() {
assertThat(controller).isNotNull();
}
@Test
void getRequest() throws Exception {
// this doesn't work
this.mvc.perform(get("/currencies")).andExpect(HttpStatus.ACCEPTED);
//tried this too
RequestBuilder request = get("/currencies");
MvcResult result = mvc.perform(request).andReturn();
assertThat(result.getResponse().getStatus(), 200);
}
}
我该如何进行这项工作?我在 Google 和 youtube 上无休止地搜索。没有什么能帮助我。我错过了一些东西,我确定
解决方案
推荐阅读
- javascript - 如何从 Node.js 中的 Post 请求中获取收据数据
- c# - C# RestSharp RestClient 在向同一 API 发出 100 次请求后失败
- javascript - 如何根据第二个响应用axios更新第一个响应的内容
- node.js - _ 未定义 - NodeJS + UnderscoreJS
- c# - 如何使用文本框创建多选下拉列表
- javascript - 从常规函数访问 React 上下文
- javascript - 如何更改地图视图的方向以导航用户?
- sql - SSRS 服务器模拟错误 - 无法获取有关 Windows NT 组/用户的信息
- python - Python - 尝试从另一个文件调用函数(使用 python-pptx)
- delphi-7 - 如何使 Delphi7 应用程序崩溃?