java - Spring MVC Controller 测试失败 - 未设置内容类型

标签 java spring-mvc testing gradle

当我将我的申请表从 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/

相关文章:

java - 链接 Activity 会导致 OOM

java - 我需要帮助理解 java 中 Timer 类的 scheduleAtFixedRate 方法

java - 线程并发和同步

java - YouTube api(数据)尝试运行示例代码以进行搜索

java - Spring转换器、 validator 和DataBinder : how to handle multivalued bean fields individually?

testing - selenium web 驱动程序如何知道新窗口何时打开然后恢复执行

testing - 我如何才能仅在一定比例的用户群中测试新功能?

JSP 中的 Spring null 应用程序上下文

spring - java.lang.ClassNotFoundException:org.hibernate.bytecode.instrumentation.internal.FieldInterceptionHelper Java Spring异常

java - Silk Test Open Agent 锁定跟踪文件