Spring MVC返回406进行控制器测试

时间:2017-11-14 20:30:38

标签: java spring spring-mvc spring-boot junit

我有以下项目树:

├── app
│   ├── build.gradle
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── child
│       │   │       └── app
│       │   │           └── Application.java
│       │   └── resources
│       │       └── application-default.yaml
│       └── test
│           └── java
│               └── child
│                   └── app
│                       └── ApplicationTest.java
├── build.gradle
└── childA
    ├── build.gradle
    └── src
        ├── main
        │   └── java
        │       └── child
        │           └── a
        │               ├── CoreConfig.java
        │               ├── PingController.java
        │               └── SpringWebMvcInitializer.java
        └── test
            └── java
            │   └── child
            │       └── a
            │           └── PingControllerTest.java
            └── resources
                └── application-core.yml

我有以下测试类:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)
@WebAppConfiguration
@ActiveProfiles({ "core" })
public class PingControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPing() throws Exception {
this.mockMvc.perform(get(CoreHttpPathStore.PING)).andDo(print());
this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON_UTF8_VALUE).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)).andExpect(status().isOk());
    }

}

我有以下PingController.java

@RestController
public class PingController {

    @RequestMapping(value = CoreHttpPathStore.PING, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Map<String, Object>> ping() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "Welcome to our API");
        map.put("date", new Date());
        map.put("status", HttpStatus.OK);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

}

我有以下SpringWebMvcInitializer.java

@ComponentScan
public class SpringWebMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{ "/" };
    }

}

预期

我希望测试能够通过http代码200传递。

结果

我得到406和以下print()

04:29:47.488 [main] DEBUG org.springframework.test.web.servlet.TestDispatcherServlet - Successfully completed request

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

Handler:
             Type = com.kopaxgroup.api.core.controller.PingController

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotAcceptableException

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

FlashMap:
       Attributes = null

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

问题

所以这是我的问题:

  • 我做了一些谷歌搜索,大多数答案说上下文需要加载@ContextConfiguration("/test-context.xml"),我使用JAVA配置,我没有XML。我的SpringWebMvcInitializer.java替换了该文件并且是否正确替换了它?

  • 为什么我会收到406错误?

3 个答案:

答案 0 :(得分:1)

我认为简单的方法是创建TestApplication类并将其放入/childA/test/java/a

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {
}

我认为如果使用Spring Boot,最好使用以下注释进行测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"core"})
public class PingControllerTest {
...
}

答案 1 :(得分:0)

您可以尝试添加内容类型。     this.mockMvc.perform(get(CoreHttpPathStore.PING).accept(MediaType.APPLICATION_JSON)).contentType(MediaType.APPLICATION_JSON))andExpect(status().isOk());

答案 2 :(得分:0)

尝试执行以下步骤:

@Configuration
    @EnableWebMvc
    public static class PingControllerTestConfiguration {

        @Bean
        public PingController myController() {
            return new PingController();
        }
    }

更改

@ContextConfiguration(classes = { PingController.class, SpringWebMvcInitializer.class }, initializers = ConfigFileApplicationContextInitializer.class)

@ContextConfiguration