在此方法测试中,我必须向 / orders 发送Post请求。它期望收到:
如果产品列表的尺寸为1
@Test
public void CPlaceOrderTrue() throws Exception {
String json = "{\"email\": \"a@b.com\",\"products\": [{\"id\": 0,\"name\": \"New Item\",\"price\": 10}]}";
mock.perform(post("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andExpect(jsonPath("$.email", Matchers.is("a@b.com")))
.andExpect(jsonPath("$.products.*", Matchers.hasSize(1)))
.andExpect(status().isOk());
}
但是当我午餐课程作为JUnit测试时,它给了我这个:
java.lang.AssertionError: No value at JSON path "$.email"
我也尝试请求一个空的帖子(只是“ {}” ),但这给了我同样的错误。
此Post请求测试可通过以下方法工作:
@RequestMapping(value="", method=RequestMethod.POST)
public ResponseEntity<Order> placeOrder(@RequestBody Order o)
throws FileNotFoundException, IOException {
if(o.getEmail() == null || o.getProducts() == null || o.getProducts().size() == 0)
return new ResponseEntity<Order>(HttpStatus.BAD_REQUEST);
boolean check;
for(int i=0; i<o.getProducts().size(); i++) {
check = false;
for(int j=0; j<Init.products.size(); j++) {
if(o.getProducts().get(i).getId() == (Init.products.get(i).getId())){
check = true;
}
}
if(!check) return new ResponseEntity<Order>(HttpStatus.BAD_REQUEST);
}
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
int newID = Init.orders.size();
Order newOrder = new Order(newID, o.getEmail(), o.getProducts(), format.format(date));
Init.orders.add(newOrder);
out = new ObjectOutputStream(new FileOutputStream(Init.ordersFile));
out.writeObject(Init.orders);
return new ResponseEntity<Order>(newOrder, HttpStatus.OK);
}