2016-11-27 136 views
4

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

我的问题是如何在运行测试时获得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 
+0

下你的球衣休息enpoints你是不是也使用Web安全配置为您

import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.context.annotation.Configuration; /** * @author Iftikhar Ul Hassan */ @Configuration @ApplicationPath("/rest") public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages("package.path.where.HealthController.resides"); } } 

样本类? –

+1

当创建测试的上下文时,您的控制器可能没有被Spring拾取。尝试使用'@SpringBootTest'结合'@AutoConfigureMockMvc',如下所述:http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/ WebMvcTest.html。 – Tom

+0

当* curl */health'端点时,哪一个会被调用:Spring Boot执行器的运行状况端点还是您的自定义控制器?恕我直言,执行器的终点是'curl -i http:// localhost:8080/health'成功并且你的控制器根本没有被拾起的原因 –

回答

2

当您使用JAX-RS,而不是Spring MVC中的@Path@GET注释来看。 @WebMvcTest专门用于测试使用Spring MVC实现的Web切片。它过滤掉了不是Spring MVC控制器的组件,因此它不适用于使用JAX-RS实现的Web API。

+0

是的,我正在使用JAX-RS。我创建了一个Spring Controller,然后工作。尽管如此,我仍然在上面的注释中使用@Tom的提示测试了JAX-RS控制器(初始问题) – Avec

+0

我之前正在玩这个想法(当我尝试将它用于restdocs时),并且它_is_可能。您需要注册[ServletContainer]的一个实例(https://github.com/spring-projects/spring-boot/blob/v1.4.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/ springframework/boot/autoconfigure/jersey/JerseyAutoConfiguration.java#L149)(这是一个过滤器和一个servlet)与MockMvcBuilders。我之前尝试重现相同的结果,但我无法做到。不确定我上次做了什么。所有我记得的是,这真的很hacky :-) –

+0

@peeskillet有趣,可能是我后。不好,你不记得。虽然哈克很少会好。 – Avec

0

当我看着你的控制器类时,有点混乱。您正在使用@Controller,然后使用@Path@GET注释,这意味着您正在使用Jersey。我会建议使用@Component。虽然,@Controller延伸@Component但仍然....

无论如何,您应该使用org.springframework.boot.test.web.client.TestRestTemplate测试您的其余资源。例如

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class SpringBootApplicationTests { 


    @Autowired 
    private TestRestTemplate restTemplate; 

    @Test 
    public void contextLoads() { 
     final ResponseEntity<Health> entity = this.restTemplate.getForEntity("/health", Health.class); 
     assertThat(entity.getStatusCode()).isEqualTo(OK); 
    } 

} 

这应该适合你。

我加入的pom.xml这显示了依赖关系,你需要添加到你的pom.xml

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>no.hassan.bones</groupId> 
    <artifactId>spring-boot-backbone</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <name>spring-boot-exmaple-jersey-mvc</name> 
    <description>Doing Spring Boot with jersey and spring web-mvc</description> 

    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.4.2.RELEASE</version> 
     <relativePath/> <!-- lookup parent from repository --> 
    </parent> 

    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
     <java.version>1.8</java.version> 
    </properties> 

    <dependencies> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-actuator</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-web</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-jersey</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-test</artifactId> 
      <scope>test</scope> 
     </dependency> 

    </dependencies> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId>    
      </plugin> 
     </plugins> 
    </build> 


</project> 

正如你可以看到,我使用的是两个Spring MVC的即spring-boot-starter-web和球衣,以及spring-boot-starter-jersey 。请记住,你需要添加一个@Configuration类,注册你的Jerse休息端点。下面是现在,你可以成为/rest/**

+0

我试过这个,但得到了'不满意的依赖关系通过字段'restTemplate'表示;' – Avec

+0

我现在看到,我不清楚我使用的是JAX-RS。我已更新到我的帖子。 – Avec

+0

您是否尝试删除'@ Contorller'注释并尝试'@ Component'? 很高兴看到你的pom.xml – Hasasn