在此方法测试中,我必须对/ orders执行Post请求 . 它希望得到:

  • 字符串字段("email")

  • ArrayList字段("products")

  • 如果产品列表的大小为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);
}