简体   繁体   中英

spring boot rest api test getting 404 error

I am trying to create a basic spring boot application (JDK 1.8) with a REST API . The following is my application code

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

    @SpringBootApplication
    public class OrderApplication {

        public static void main(String[] args) {
            SpringApplication.run(OrderApplication.class, args);
        }

I have added a controller as follows

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/api")
public class OrderRestController {

    private OrderService orderService;


    //injecting order service {use constructor injection}
    @Autowired
    public OrderRestController(OrderService theCarService) {
        orderService=theCarService;
    }


    //expose "/orders" and return the list of orders.
    @GetMapping("/orders")
    public List<Order> findAll(){
        return orderService.findAll();
    }
}

Test code is:

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import com.fasterxml.jackson.databind.ObjectMapper;

@RunWith(SpringRunner.class)
@WebMvcTest(OrderRestController.class)
@AutoConfigureMockMvc
public class OrderRestControllerTest {

  @Autowired
  private MockMvc mvc;

  @MockBean
  private OrderService service;

  @Test
  public void getAllOrdersAPI() throws Exception
  {
    mvc.perform( MockMvcRequestBuilders
        .get("/orders")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath("$.orders").exists())
        .andExpect(MockMvcResultMatchers.jsonPath("$.orders[*].orderId").isNotEmpty());
  }

}

Service Implementation:

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class OrderServiceImpl implements OrderService {

    private OrderDAO orderDao;

    //injecting order dao {use constructor injection}
    @Autowired
    public OrderServiceImpl(OrderDAO theOrderDao) {
        orderDao=theOrderDao;
    }

    @Override
    public List<Order> findAll() {
        return orderDao.findAll();
    }


}

When I run this application, it starts successfully and also I am able to see my populated mock data.

Console Log

    HTTP Method = GET
      Request URI = /orders
       Parameters = {}
          Headers = [Accept:"application/json"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2019-02-24 14:55:56.623  INFO 276 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Anyone can help me about that? Much appreciated!

Thanks

I can see 2 problems:

  1. Probably, you meant:
MockMvcRequestBuilders.get("/api/orders")
  1. In order to assert that controller returns something, you should stub call to the service :
@Test
public void getAllOrdersAPI() throws Exception {
   Order order = create expected order object
   when(service.findAll()).thenReturn(Arrays.asList(order));
   // rest of the test
}

Your test should look like this

@Test
  public void getAllOrdersAPI() throws Exception
  {
    mvc.perform( MockMvcRequestBuilders
        .get("/api/orders")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath("$.orders").exists())
        .andExpect(MockMvcResultMatchers.jsonPath("$.orders[*].orderId").isNotEmpty());
  }

You missed to add /api in the get URL. I don't see anything else. Let me know if it helps else I will go and compile it for you on my machine.

Your mockResponse is 404.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM