4

我正在使用 spring test mvc 框架为控制器编写一个测试。我正在尝试测试一个发布请求,它会生成 JSON。实际代码正在运行,但测试失败。

我收到错误状态预期 200 但收到 415 这意味着不支持的媒体类型。我检查了网上的所有示例,看来我的实现是正确的。请帮帮我。

MyTestcase TestStringPost() 运行成功,但 TestJSONPost 失败。

我正在使用 Spring 3.2

我的控制器

@Controller
public class HomeController {


@RequestMapping(value = "/v1/checkstringvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody void testStringPost(@RequestBody String value) {
    logger.info("Welcome home! The client locale is {}.");
}

@RequestMapping(value = "/v1/checkjsonvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String testJSONPost(@RequestBody Map<String, String> userMap) {
    System.out.println("Inside test jsonpost controller");
    logger.info("Welcome home! The client locale is {}.");
    return "Success";
 }
}

这是我的测试控制器

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class HomeControllerTest {


@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

private static final String PROVIDER_A = "PROVIDER_A";

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
        MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Configuration
public static class TestConfiguration {

    @Bean
    public HomeController simpleController() {
        return new HomeController();
    }
}

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

@Test
public void testStringPost() throws Exception {

    final String createJson = "hello";

    ResultActions resultActions = mockMvc.perform(post(
            "/v1/checkstringvalue").contentType(MediaType.TEXT_PLAIN)
            .content(createJson));

    resultActions.andDo(print());
    resultActions.andExpect(status().isOk());
}

@Test
public void testjsonPost() throws Exception {

    System.out.println("Inside testjsonpost");
    final String createJson = "{\"name\":\"hello\",\"email\":\"hello@example.com\"}";

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode userJson = objectMapper.createObjectNode();
    userJson.put("name", "tarun");
    userJson.put("email", "tarun@gmail.com");

    ResultActions resultActions = mockMvc
            .perform(post("/v1/checkjsonvalue")
                    .contentType(APPLICATION_JSON_UTF8)
                    .accept(APPLICATION_JSON_UTF8)
                    .content(objectMapper.writeValueAsBytes(userJson)));

    resultActions.andDo(print());
    resultActions.andExpect(status().isOk());
}
}
4

3 回答 3

9

好的,所以有了

perform(post("/myapi").contentType(MediaType.APPLICATION_JSON).content("{\"mykey\":\"myvalue\"}"))   

很重要。

但是还要检查您的控制器:如果它缺少任何这些注释,它将不起作用:

@EnableWebMvc
@Controller
public class MyController {
    @RequestMapping(value="/myapi", method=RequestMethod.POST)
    public void postOnApi(@RequestBody MyWidget myWidget) {
    }
}

@EnableWebMvc @Controller 和 @RequestBody 都需要(在我的实验中)来消除 415 状态代码错误。

于 2014-08-29T17:52:43.150 回答
0

您的测试代码:

ResultActions resultActions = mockMvc
            .perform(post("/v1/checkjsonvalue")
                    .contentType(APPLICATION_JSON_UTF8)
                    .accept(APPLICATION_JSON_UTF8)
                    .content(objectMapper.writeValueAsBytes(userJson)));

好像加了contentType()header,但是你的源码中没有consumes属性@RequestMapping

@RequestMapping(value = "/v1/checkjsonvalue", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody String testJSONPost(@RequestBody Map<String, String> userMap) {
    System.out.println("Inside test jsonpost controller");
    logger.info("Welcome home! The client locale is {}.");
    return "Success";
 }

我认为,如果您在测试用例中取出 contentType() 或在源代码中添加消耗,那么它可能会起作用。

于 2014-05-01T10:16:10.733 回答
0

如果您在 spring mvc 项目中使用基于 xml 的配置,请确保已将@EnableWebMvc放在控制器上。

于 2020-09-07T07:31:43.497 回答