MockMvc HttpMediaTypeNotSupportedException: 不支持内容类型 'application/json'

12

我收到了以下异常:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported

    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.readWithMessageConverters(HandlerMethodInvoker.java:653)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestBody(HandlerMethodInvoker.java:612)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:361)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)

我的测试看起来像这样:

public class AvailabilityControllerTest extends BaseTest {   
    @Test
    public void createAvailability() throws Exception {
        final String createAvailabilityEndPoint = "/api/v4/companies/123/availabilities";
        final String responseName = "availabilityResponseDTO";

        AvailabilityDTO availabilityDTO = new AvailabilityDTO();

        MvcResult mvcResult = mockMvc.perform(
                MockMvcRequestBuilders.post(createAvailabilityEndPoint)
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .accept(MediaType.APPLICATION_JSON_VALUE)
                        .content(new ObjectMapper().writeValueAsString(availabilityDTO)))
                .andExpect(MockMvcResultMatchers.status().isCreated())
                .andReturn();
    }

使用BaseTest作为:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestConfiguration.class)
@AutoConfigureMockMvc
public class BaseTest {

    @Autowired
    protected MockMvc mockMvc;

}

测试配置看起来像这样:

@Configuration
@ComponentScan(
        basePackages = "com.app",
        excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = App.class)
        }
)
public class TestConfiguration {

    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }
}

AvailabilityController看起来像这样:

@RestController
@RequestMapping("/api/v4/companies")
public class AvailabilityController {

    public static final String ACCEPT_APP_JSON = "Accept=" + AcceptableMediaType.APPLICATION_JSON;

    @Autowired
    private AvailabilityFacade availabilityFacade;

@RequestMapping(value = "/{companyId}/employees/{employeeId}/availabilities", method = RequestMethod.GET)
    public List<AvailabilityEventResponseDTO> getUserAvailabilities(@PathVariable String companyId,
                                                                    @PathVariable String employeeId) {
        return availabilityFacade.getUserAvailabilities(employeeId);
    }

    @RequestMapping(value = "/{companyId}/availabilities", method = RequestMethod.POST, headers = ACCEPT_APP_JSON, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<AvailabilityResponseDTO> createAvailability(@PathVariable String companyId,
                                                                      @Valid @RequestBody AvailabilityDTO availabilityDTO) {
        return new ResponseEntity<>(
                availabilityFacade.createAvailability(companyId, availabilityDTO),
                HttpStatus.CREATED
        );
    }
}

基本上,使用MockMvc时GET请求可以正常工作,但POST请求不行,会返回HttpMediaTypeNotSupportedException。我尝试在请求和控制器中添加和删除接受和内容类型的标头,但似乎没有用。

这个问题似乎与Spring集成测试和MockMvc一起使用会抛出org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型'application/json'有关,但是在这种情况下删除TestConfiguration中的excludeFilters不允许Spring解释上下文。此外,我不确定Karl R所说的“在我的类路径中包含serverruntime”是什么意思。

感谢任何帮助。

2个回答

26
我认为你应该在TestConfiguration中添加@EnableWebMvc。
@Configuration
@ComponentScan(
     basePackages = "com.app",
    excludeFilters = {
            @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, 
              classes = App.class)
    }
)
@EnableWebMvc
public class TestConfiguration {

3
最令人恼火的错误之一,却没有适当的错误信息。谢谢! - Marcin T.P. Łuczyński

1
在我的情况下,问题是我没有设置contentType,所以将其设置为JSON类型解决了我的问题。
...
.contentType(MediaType.APPLICATION_JSON)
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接