我正在使用 Spring Boot 和 Mockito 运行单元测试,我正在测试 RESTful 服务。当我尝试测试 GET 方法时,它成功运行,但是当我尝试测试 POST 方法时,它失败了。我应该怎么做才能解决这个问题?提前致谢!
这是 REST 控制器的代码:
package com.dgs.restfultesting.controller;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.dgs.restfultesting.business.ItemBusinessService;
import com.dgs.restfultesting.model.Item;
@RestController
public class ItemController {
@Autowired
private ItemBusinessService businessService;
@GetMapping("/all-items-from-database")
public List<Item> retrieveAllItems() {
return businessService.retrieveAllItems();
}
@PostMapping("/items")
public Item addItem(@RequestBody Item item) {
Item savedItem = businessService.addAnItem(item);
return savedItem;
}
}
业务层:
package com.dgs.restfultesting.business;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dgs.restfultesting.data.ItemRepository;
import com.dgs.restfultesting.model.Item;
@Component
public class ItemBusinessService {
@Autowired
private ItemRepository repository;
public Item retrieveHardcodedItem() {
return new Item(1, "Book", 10, 100);
}
public List<Item> retrieveAllItems() {
List<Item> items = repository.findAll();
for (Item item : items) {
item.setValue(item.getPrice() * item.getQuantity());
}
return items;
}
public Item addAnItem(Item item) {
return repository.save(item);
}
}
MMMHUHU
相关分类