gpt4 book ai didi

java - Spring Boot Restcontroller 作为单元测试中的内部类(webmvctest)

转载 作者:行者123 更新时间:2023-12-04 10:32:03 26 4
gpt4 key购买 nike

是否有可能在测试上下文中声明一个 RestController ,最好是作为 Spring Boot 测试的内部类?我确实需要它用于特定的测试设置。我已经尝试以下简单示例作为 POC:

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureWebClient;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;


@ExtendWith(SpringExtension.class)
@WebMvcTest(ExampleTest.TestController.class)
@AutoConfigureMockMvc
@AutoConfigureWebClient
public class ExampleTest {

@Autowired
private MockMvc mockMvc;

@Test
public void exampleTest() throws Exception {
ResultActions resultActions = this.mockMvc
.perform(get("/test"));
resultActions
.andDo(print());
}

@RestController
public static class TestController {
@GetMapping("/test")
public String test() {
return "hello";
}
}

}


但是,通过 MockMvc 测试端点会提供 404。我错过了什么吗?

最佳答案

问题是,TestController未加载到应用程序上下文。可以通过添加解决

@ContextConfiguration(classes= ExampleTest.TestController.class)



测试将如下所示:
@ExtendWith(SpringExtension.class)
@WebMvcTest(ExampleTest.TestController.class)
@ContextConfiguration(classes= ExampleTest.TestController.class)
@AutoConfigureMockMvc
@AutoConfigureWebClient
public class ExampleTest {

@Autowired
private MockMvc mockMvc;

@Test
public void exampleTest() throws Exception {
ResultActions resultActions = this.mockMvc
.perform(get("/test"));
resultActions
.andDo(print());
}

@RestController
public static class TestController {
@GetMapping("/test")
public String test() {
return "hello";
}
}

}

和输出:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"5"]
Content type = text/plain;charset=UTF-8
Body = hello
Forwarded URL = null
Redirected URL = null
Cookies = []

关于java - Spring Boot Restcontroller 作为单元测试中的内部类(webmvctest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60372144/

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