gpt4 book ai didi

java - Spring Boot 1.4.2 @WebMvcTest 返回状态 404

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:31:48 24 4
gpt4 key购买 nike

我正在使用 Spring Boot 1.4.2 和 Jersey (jax-rs) 创建一个 REST Controller 。我遵循了有关如何测试 REST Controller 的文档 (Testing the Spring MVC slice)。但是我的测试返回 404,我似乎无法找出原因。这里的 Controller 被简化了,但问题依然存在。

我的问题是如何在运行测试时获取200状态?

HealthController.java

@Controller
@Path("/health")
public class HealthController {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Health health() {
return Health.up().build();
}
}

运行服务器并进行查询给了我这个

%> curl -i http://localhost:8080/health
HTTP/1.1 200
X-Application-Context: application
Content-Type: application/json
Content-Length: 21
Date: Sun, 27 Nov 2016 15:22:30 GMT

{
"status" : "UP"
}%

HealthControllerTest.java

@RunWith(SpringRunner.class)
@WebMvcTest(HealthController.class)
public class HealthControllerTest {

@Autowired
private MockMvc mockMvc;

@Test
public void health() throws Exception {
mockMvc.perform(get("/health").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()); // 200 expected
}
}

这是我在运行测试时得到的结果

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.4.2.RELEASE)

2016-11-27 16:22:08.254 INFO 9029 --- [ main] no.avec.controller.HealthControllerTest : Starting HealthControllerTest on ducati.local with PID 9029 (started by avec in /Users/avec/Projects/RESTdemo)
2016-11-27 16:22:08.257 DEBUG 9029 --- [ main] no.avec.controller.HealthControllerTest : Running with Spring Boot v1.4.2.RELEASE, Spring v4.3.4.RELEASE
2016-11-27 16:22:08.257 INFO 9029 --- [ main] no.avec.controller.HealthControllerTest : No active profile set, falling back to default profiles: default
2016-11-27 16:22:09.294 INFO 9029 --- [ main] no.avec.controller.HealthControllerTest : Started HealthControllerTest in 1.421 seconds (JVM running for 2.132)

MockHttpServletRequest:
HTTP Method = GET
Request URI = /health
Parameters = {}
Headers = {Accept=[application/json]}

Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = null
View = null
Model = null

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

java.lang.AssertionError: Status
Expected :200
Actual :404

最佳答案

根据 @Path@GET 注释判断您使用的是 JAX-RS 而不是 Spring MVC。 @WebMvcTest专门用于测试使用Spring MVC实现的web slice。它过滤掉不是 Spring MVC Controller 的组件,因此它不能与使用 JAX-RS 实现的 Web API 一起使用。

关于java - Spring Boot 1.4.2 @WebMvcTest 返回状态 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40830854/

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