0

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.

Sagarmichael
  • 1,624
  • 7
  • 24
  • 53
  • In test you are saying `this.mockMvc.perform(post("/create")` i.e. post request whereas you want to test `GET @GetMapping createOrders` I think you should check that. Also if you want to use `when() thenReturn()` create a Customer object and send it back when findOne is called. – rdj7 Jan 15 '18 at 07:00

1 Answers1

0

@DataJpaTest is for repository test. In this case, @DataJpaTest is useless.
And, in test class, you missed

@Autowired
private OrderRepository orderRepository;
Min Hyoung Hong
  • 1,102
  • 9
  • 13