【发布时间】:2018-06-23 14:56:20
【问题描述】:
我在尝试测试时遇到问题
下面的REST方法
@GetMapping
@RequestMapping("/create")
ResponseEntity<Order> createOrders(@RequestBody String body) {
ObjectMapper mapper = new ObjectMapper();
try{
Map<String,Object> mapBody = mapper.readValue(body,Map.class);
Long cusId = Long.valueOf((int)mapBody.get("customer_id"));
Customer customer = customerRepository.findOne(cusId);
Product product = productRepository.findByProductName((String)mapBody.get("product_name"));
Order order = new Order(customer,product,(int)mapBody.get("quantity"));
orderRepository.saveAndFlush(order);
return new ResponseEntity(order, HttpStatus.OK);
}
catch(Exception e){
e.printStackTrace();
return new ResponseEntity("error with original port", HttpStatus.EXPECTATION_FAILED);
}
}
我已经尝试了很多东西,但似乎没有任何效果。 调用 REST 方法可以正常工作,但似乎我可以使用 @AutoConfigureMockMvc 或 @DataJpaTest 在我的测试中
我的代码目前如下
@SpringBootTest
@AutoConfigureMockMvc
@DataJpaTest
public class OrderTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ProductRepository productRepositoryTest;
@Autowired
private CustomerRepository customerRepositoryTest;
@Test
public void submitNewOrdersForBricks() {
try {
Customer cus1 = new Customer("cus1");
customerRepositoryTest.saveAndFlush(cus1);
Product pro1 = new Product("brick1","red brick",0.96);
productRepositoryTest.saveAndFlush(pro1);
this.mockMvc.perform(post("/create")
.content("{\"customer_id\":"+cus1.getCustomerId()+",\"product_name\":\"brick1\",\"quantity\":150}")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print()).andExpect(status().isCreated())
.andExpect(jsonPath("$.order_id").value(1));
}
catch(Exception e){
e.printStackTrace();
}
}
}
我也尝试过使用
when(customerRepository.findOne(cusId)).thenReturn(cus1);
这对我的控制器没有任何影响。 请注意,控制器方法 createOrders 仅在我删除 @DataJpaTest 时调用,但不会为客户和产品创建 ID。
任何帮助都会很棒。
【问题讨论】:
-
在测试中你说
this.mockMvc.perform(post("/create")即发布请求而你想测试GET @GetMapping createOrders我认为你应该检查一下。此外,如果您想使用when() thenReturn()创建一个 Customer 对象并在调用 findOne 时将其发回。
标签: unit-testing spring-boot spring-data-jpa spring-web