Java 让我的@Test GET请求在Spring Boot中工作

Java 让我的@Test GET请求在Spring Boot中工作,java,spring-boot,api,testing,Java,Spring Boot,Api,Testing,我是初学者。我已经在SpringBoot中使用java创建了一个API,我想测试GET请求是否返回200。我对检查返回的内容(JSON对象)不感兴趣,我只想检查这个连接是否工作。到目前为止,我已尝试过此代码: @Test void getRequest() throws Exception { // this doesn't work because a ResultMatcher is needed this.mvc.perform(get("

我是初学者。我已经在SpringBoot中使用java创建了一个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执行get请求,并期望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);

    }


}


我该怎么做?我一直在谷歌和youtube上搜索。什么也帮不了我。我遗漏了一些东西,我确信

您正在查找
和预期(status().isAccepted())
。我强烈建议大家看一下官方教程。您好,您的建议非常接近!单元测试失败,因为预期值返回202,而实际值为200。我用这个
status()修复了它。is2xxsuccesful()
成功了!非常感谢,伙计