I am having issues trying to test
THe following REST method
@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);
}
}
I have tried numrous things so for and nothing seems to work. Doing a call to the REST method works fine but it seems I can use either @AutoConfigureMockMvc or @DataJpaTest in my testing
My code is currently as follows
@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();
}
}
}
I have also tried using
when(customerRepository.findOne(cusId)).thenReturn(cus1);
This did not have any effect in my controller. Please note that the controller method createOrders is only called when I remove @DataJpaTest, but then IDs are not created for customer and product.
Any help would be great.