当我将我的申请表从 Maven (Eclipse) 移动到 Gradle (InteliJ) 时,我所有的 Controller 测试都停止工作。使用 Maven 对旧应用程序进行测试。
我的 Controller 方法:
@RequestMapping(value = "submit", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody FormResponse submitForm(@RequestBody TagData form) {
try {
tagService.saveTag(form);
} catch (BusinessException ex) {
return FormResponse.error(ex);
}
return FormResponse.success("admin.tag.saved");
}
我的测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/pl/dk/web/controllers/controllers-test-context.xml"})
@WebAppConfiguration
public class TagControllerTest {
@Autowired
TagController controller;
@Autowired
WebApplicationContext webContext;
@Autowired
TagManagerService tagService;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webContext).build();
EasyMock.reset(tagService);
}
@Test
public void testSave() throws Exception {
TagData form = new TagData();
form.setName("Test tag");
form.setDescription("Test description");
EasyMock.expect(tagService.saveTag(form)).andReturn(1L);
controller.tagService = tagService;
RequestBuilder reqBuilder = MockMvcRequestBuilders.post("/admin/recipes/tag/submit")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToString(form));
MvcResult result = mockMvc.perform(reqBuilder)
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
Assert.assertNotNull(result);
}
}
在我最坏的情况下,这个问题可能与 InteliJ 与 gradle 的集成或其他东西有关,我在这里与幽灵作斗争。谁能帮我解决这个问题?
我的错误:
java.lang.AssertionError: Content type not set
最佳答案
我找到了解决方案,尽管对我来说不是那么明显。问题与 jackson 图书馆有关。我申请的时候
testCompile 'com.fasterxml.jackson.core:jackson-databind:2.3.1'
代替
testCompile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
testCompile 'org.codehaus.jackson:jackson-core-asl:1.9.13'
一切开始工作。
关于java - Spring MVC Controller 测试失败 - 未设置内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27879044/