Can someone help on this?
I am getting the below exception(org.springframework.web.HttpMediaTypeNotSupportedException) when I run this test.
在回复中,我得到了这个标题。
Headers = {Accept = [application / octet-stream,text / plain; charset = ISO-8859-1,application / xml,text / xml,application / x-www-form-urlencoded,application / + xml,multipart / form-data,application / json; charset = UTF-8,application / + json; charset = UTF-8, / ]}
控制器中的add方法是
@RequestMapping(value = "/addTrain", method = RequestMethod.POST)
public @ResponseBody void addTrain(@RequestBody Train train) {
trainService.addTrain(train);
}
I am doing JUnit test for a method. Below is my Test class and MockHttpServletRequest and MockHttpSErvletResponse.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/config/webapp-config.xml" })
@WebAppConfiguration
public class TrainControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@InjectMocks
TrainController trainController;
@Mock
private TrainService trainService;
private final List<Train> trainList = new ArrayList<Train>();
private Train train;
@Before
public void setUp() throws Exception {
// Process mock annotations
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
train = new Train();
train.setId(12L);
train.setName("chennai");
train.setSpeed(100);
train.setDiesel(true);
Train train1 = new Train();
train1.setId(15L);
train1.setName("kovai");
train1.setSpeed(150);
train1.setDiesel(false);
trainList.add(train);
trainList.add(train1);
}
@Test
public void testAddTrainList() throws Exception {
Mockito.doNothing().when(trainService).addTrain(train);
this.mockMvc.perform(post("/trains/addTrain")).andDo(print()).andExpect(status().isOk());
}
}
MockHttpServletRequest:
HTTP Method = POST
Request URI = /trains/addTrain
Parameters = {}
Headers = {}
Handler:
Type = com.xvitcoder.angualrspringapp.controller.TrainController
Method = public void com.xvitcoder.angualrspringapp.controller.TrainController.addTrain(com.xvitcoder.angualrspringapp.beans.Train)
Async:
Was 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**
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
答案 0 :(得分:4)
您的请求必须从其中一个可接受的标题中指定Content-type标头。
尝试更改模拟请求,如下所示:
this.mockMvc.perform(post("/trains/addTrain").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
已解决的异常: Type = org.springframework.http.converter.HttpMessageNotReadableException