user3394305
user3394305

Reputation: 3

Spring MVC test

I am trying to learn spring, and I cannot find enough resources for testing, sorry for my English:) I have a controller class which returns ResponseEntity

    @RestController
    @RequestMapping("/")
    public class OrderController {

    @Autowired
    private OrderRepository rep;

    @GetMapping("/{id}")
    public ResponseEntity<?> getOrderById(@PathVariable("id") String id){
        Order or = rep.findById(id).get();
        return ResponseEntity.ok(or); }
    @PostMapping("/add")
    public ResponseEntity<?> addOrder(@RequestBody Order order){
        rep.save(order);
        return ResponseEntity.ok(order);
}

I am trying to test with

 @RunWith(SpringRunner.class)
 @WebMvcTest(OrderController.class)
 public class OrderControllerTest {

    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private OrderRepository orderRepository;
    @Test
    public void shouldPresistOrder() throws Exception {

        this.mockMvc.perform(get("/ORD00001").accept("application/json"))
        .andExpect(status().isOk());}}

I get status expected<200> but was<404> Do I need to create an Order instance first, because it is a quite large class with lots of variables ? What are the ways of testing endpoints? Are there any books or online resources just for MVC testing purposes? Many thanks

Upvotes: 0

Views: 99

Answers (1)

nayan kakati
nayan kakati

Reputation: 83

You are mocking the OrderRepository class but there are no rules associated with it, create a dummy Order and Add the rule like this when(orderRepository.findById(<id in the dummy order>)).thenReturn(DummyOrder) In this way, you are setting the rules for OrderRepository to behave according to your needs.

Upvotes: 1

Related Questions