java Spring MVC 测试导致 415 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32838699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:51:42  来源:igfitidea点击:

Spring MVC testing results in 415 error

javaspringspring-mvc

提问by Ivan Mushketyk

I am trying to write integration tests for my REST API implemented with Spring MVC.

我正在尝试为使用 Spring MVC 实现的 REST API 编写集成测试。

Here is my REST implementation:

这是我的 REST 实现:

import org.myproject.api.input.ProjectInput;
import org.myproject.dao.ProjectsDao;
import org.myproject.model.Project;
import org.myproject.model.Projects;
import org.myproject.util.Exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/projects")
public class ProjectsApi {

    @Autowired
    private ProjectsDao projectsDao;

    ...

    @RequestMapping(value = "/",
        method = RequestMethod.POST,
        produces = {"application/json"},
        consumes = {"application/json"})
    public @ResponseBody Project addProject(@RequestBody ProjectInput projectInput) throws IOException {
        logger.info("Add project");
        Project project = projectInput.createProject();
        projectsDao.add(project);

        return project;
     }
}

Here is ProjectInput class:

这是 ProjectInput 类:

@XmlRootElement
public class ProjectInput {
    private String name;
    private String description;

    // Constructor to make JSON converter happy
    private ProjectInput() {}

    public ProjectInput(String name, String description) {
        this.name = name;
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }
    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

And here is my test:

这是我的测试:

import com.fasterxml.Hymanson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openboard.api.input.ProjectInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath*:applicationContext.xml"})
public class TestProjectsApi {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testAddProject() throws Exception {
        ProjectInput input = new ProjectInput("name", "description");
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(input);
        // json value is: {"name":"name","description":"description"}

        mockMvc.perform(post("/projects/")
            .contentType(MediaType.APPLICATION_JSON)
            .content(json.getBytes()))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }
}

Unfortunately I receive the following error:

不幸的是,我收到以下错误:

org.myproject.api.TestProjectsApi > testAddProject FAILED
    java.lang.AssertionError: Status expected:<200> but was:<415>
        at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
        at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
        at org.springframework.test.web.servlet.result.StatusResultMatchers.match(StatusResultMatchers.java:653)
        at org.springframework.test.web.servlet.MockMvc.andExpect(MockMvc.java:152)
        at org.myproject.api.TestProjectsApi.testAddProject(TestProjectsApi.java:48)

I execute the tests in a terminal using the following Gradle command:

我使用以下 Gradle 命令在终端中执行测试:

./gradlew --daemon test --info

UPD. I've added a print() to the request to see what is being sent/received:

更新。我在请求中添加了一个 print() 以查看正在发送/接收的内容:

org.myproject.api.TestProjectsApi > testAddProject STANDARD_OUT

    MockHttpServletRequest:
             HTTP Method = POST
             Request URI = /projects/
              Parameters = {}
                 Headers = {Content-Type=[application/json]}

                 Handler:
                    Type = org.myproject.api.ProjectsApi

                   Async:
           Async started = false
            Async result = null

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

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

                FlashMap:

    MockHttpServletResponse:
                  Status = 415
           Error message = null
                 Headers = {Accept=[application/octet-stream, */*, text/plain;charset=ISO-8859-1, */*, application/xml, text/xml, application/*+xml, application/x-www-form-urlencoded, multipart/form-data]}
            Content type = null
                    Body = 
           Forwarded URL = null
          Redirected URL = null
                 Cookies = []
Gradle Test Executor 1 finished executing tests.

回答by tokosh

I had a similar case and I could solve it by adding both header-accept AND content-type.

我有一个类似的案例,我可以通过添加 header-accept 和 content-type 来解决它。

Headers = {Accept=[application/json;charset=UTF-8], 
                   Content-Type=[application/json;charset=UTF-8]}

In the test module:

在测试模块中:

MediaType MEDIA_TYPE_JSON_UTF8 = new MediaType("application", "json", java.nio.charset.Charset.forName("UTF-8"));
MockHttpServletRequestBuilder request = post("/myPostPath");
request.content(json);
request.locale(Locale.JAPANESE);
request.accept(MEDIA_TYPE_JSON_UTF8);
request.contentType(MEDIA_TYPE_JSON_UTF8);
mockMvc.perform(request)
    .andDo(print())
    .andExpect(status().isOk());

First I only put request.accept(..). But after adding request.contentType(..)it finally worked.

首先我只放了request.accept(..). 但添加后request.contentType(..)它终于奏效了。

回答by Jeremy Ferguson

I ran into this issue and was able to fix it by adding the @EnableWebMvc annotation to my test's SpringContext class.

我遇到了这个问题,并且能够通过将 @EnableWebMvc 注释添加到我的测试的 SpringContext 类来修复它。

回答by Nikolay Rusev

Hello change your controller's method params consumes and produces to:

您好,将您的控制器的方法参数消耗和生产更改为:

consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE

and your test case to

和你的测试用例

@Test
    public void testAddProject() throws Exception {
        ProjectInput input = new ProjectInput("name", "description");
        mockMvc.perform(post("/projects/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(input)))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

EDIT:

编辑:

The problem is in your Projectclass. Missing default constructor.

问题出在你的Project班级。缺少默认构造函数。

回答by Ivan Mushketyk

I didn't have message converter bean in my applicationContext.xml.

我的 applicationContext.xml 中没有消息转换器 bean。

I had to add the following to it:

我必须添加以下内容:

<bean id="HymansonMessageConverter" `class="org.springframework.http.converter.json.MappingHymanson2HttpMessageConverter"/>`
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="HymansonMessageConverter"/>
        </list>
    </property>
</bean>

Now everything works fine.

现在一切正常。