MockMVC在springboot中没有使用驼峰

时间:2018-02-19 12:29:38

标签: apache spring-boot apache-camel

我无法成功测试我的骆驼休息控制器。当我运行它时,它目前返回状态 404而不是200

我相信我拥有所有正确的依赖关系。除了this之外,我似乎无法找到任何示例。我检查了动作书中的骆驼和多个弹簧启动文件。

完整错误

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {}
          Headers = {}

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
 <Click to see difference>


    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:665)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at je.dvs.echo.DemoApplicationTests.testCamelRestEndpoint(DemoApplicationTests.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

失败的测试,

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = MyRouter.class, secure = false)
public class DemoApplicationTests {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void contextLoads() {
    }

    @Test
    public void testCamelRestEndpoint() throws Exception{
        mockMvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("text/plain;charset=UTF-8"))
                .andExpect(content().string("Hello from Camel!"));
    }

    @Configuration
    public static class TestConfig  {
        @Bean
        public MyRouter myRouter() {
            return new MyRouter();
        }
    }

}

这是我的主要应用,

@ComponentScan
@SpringBootApplication
public class DemoApplication{

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public ServletRegistrationBean CamelServlet() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new CamelHttpTransportServlet(), "/camel/*");
        registration.setName("CamelServlet");
        return registration;
    }
}

骆驼休息控制器/路由器,

    @Component
    public class MyRouter extends RouteBuilder{

        @Override
        public void configure() {
            //Swagger api documentation
            restConfiguration()
                    .component("servlet")

                    .dataFormatProperty("prettyPrint", "true")
                    .apiContextPath("/api-docs") //<---- This is the documentation path localhost:8080/camel/api-docs
                    .apiProperty("api.title", "User API").apiProperty("api.version", "1.0.0").apiProperty("cors", "true");


            //Configure rest controller
            rest("/rest")
                    .get("/hello").produces("text/plain;charset=UTF-8")
                    .responseMessage().code(200).message("Response returned").endResponseMessage()
                    .to("direct:hello");

            //Add routes to rest controller
            from("direct:hello")
                    .transform().constant("Hello from Camel!");
        }
    }

谢谢!

1 个答案:

答案 0 :(得分:1)

我在测试Apache Camel Rest端点时遇到了同样的问题。

我最终使用TestRestTemplate

@RunWith(SpringRunner.class)
@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ComponentTest  {

    private static String HEALTH_URL = "/api/api-prefix/health";

    @Test
    public void testHealthCheck() {
        ResponseEntity<Map> health = testRestTemplate.getForEntity(HEALTH_URL, 
            Map.class);
        assertEquals("health check failed", HttpStatus.OK, 
            health.getStatusCode());
    }

}

我使用了来自camel-example-test

的示例