首页 > 解决方案 > 让我的 @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 上无休止地搜索。没有什么能帮助我。我错过了一些东西,我确定

标签: javaspring-bootapitesting

解决方案


推荐阅读