我正在爲使用spring測試mvc框架的控制器編寫一個測試。我試圖測試一個發佈請求,它會產生JSON。實際的代碼正在運行,但測試失敗。Spring MVC測試框架 - 不支持的媒體類型
我得到錯誤狀態預期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\":\"[email protected]\"}";
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode userJson = objectMapper.createObjectNode();
userJson.put("name", "tarun");
userJson.put("email", "[email protected]");
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());
}
}
嘗試將'APPLICATION_JSON_UTF8'更改爲簡單MediaType.APPLICATION_JSON –
嗨,techG,我已經完成了這項工作。 – vineet
http://stackoverflow.com/questions/13782252/spring-mvc-3-content-type-application-json-works-from-client-but-not-from-unit可能有幫助 –