Java Spring MVC测试结果为415错误
我正在尝试为用SpringMVC实现的RESTAPI编写集成测试 以下是我的REST实现:Java Spring MVC测试结果为415错误,java,spring,spring-mvc,Java,Spring,Spring Mvc,我正在尝试为用SpringMVC实现的RESTAPI编写集成测试 以下是我的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
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;
}
}
以下是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;
}
}
这是我的测试:
import com.fasterxml.jackson.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));
}
}
很遗憾,我收到以下错误:
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$10.match(StatusResultMatchers.java:653)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:152)
at org.myproject.api.TestProjectsApi.testAddProject(TestProjectsApi.java:48)
UPD。我在请求中添加了一个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.
您好将控制器的方法params consumes and Productions更改为:
consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE
您的测试用例
@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));
}
编辑:
问题出在你的
项目中。缺少默认构造函数。我的applicationContext.xml中没有消息转换器bean
我必须补充以下内容:
<bean id="jacksonMessageConverter" `class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>`
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
`
现在一切正常。我遇到了一个类似的情况,我可以通过添加header accept和content type来解决它
Headers = {Accept=[application/json;charset=UTF-8],
Content-Type=[application/json;charset=UTF-8]}
在测试模块中:
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());
首先,我只放置请求。接受(..)
。但是在添加了request.contentType(…)
之后,它终于起作用了。我遇到了这个问题,并且能够通过向我的测试的SpringContext类添加@EnableWebMvc注释来解决它。您正在接受应用程序/json;charset=UTF-8
但正在发送应用程序/json
。。。不匹配,因此不受支持。我已根据您的建议更新了代码,但仍然无效。是否发送正确的JSON?看起来正确。我已经添加了JSON输入(在测试中的注释中)。我还添加了ProjectInput类的定义。您没有属性的setter。根据您的建议修复了所有问题,但没有任何帮助。我错过了“项目”末尾的斜杠请参见editI在末尾添加了斜杠,但仍然有相同的415错误。这是不可能的,我测试了您的代码,并在我的环境中按预期工作。您正在使用哪些导入语句?您是如何运行测试用例的?哪一个是你的IDE?嗯。。。有趣。我已经将您要求的信息添加到我的问题中。您不需要手动注册转换器。如果您在类路径上有jackson库,并且您使用xml中的mvc:annotation-driven元素或@EnableWebMvc for Java Config,则默认情况下应该注册转换器。这解决了我的问题,我感到非常惊讶。很奇怪,但很有效。是的,我也很惊讶!简单的时候很好,即使看起来很奇怪。这也解决了我的问题。有人知道为什么/如何修复它吗?我没有花时间深入研究它,但是“将此注释添加到@Configuration类会从WebMvcConfigurationSupport导入Spring MVC配置”对我来说,也只是在发布列表时添加了ContentType,测试现在可以工作了。谢谢!这很好,您还可以直接在accept(..)和contentType(..)中引用静态成员MediaType.APPLICATION_JSON,无需声明自己的。wich更容易出错
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());