Spring Boot Rest API测试得到404错误

时间:2019-02-24 14:01:13

标签: java rest spring-boot testing junit

我正在尝试使用REST API创建一个基本的Spring Boot应用程序(JDK 1.8)。以下是我的应用程序代码

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);
        }

我添加了一个控制器,如下所示

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();
    }
}

测试代码为:

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());
  }

}

服务实施:

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();
    }


}

当我运行该应用程序时,它成功启动,并且我还能看到填充的模拟数据。

控制台日志

    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'

有人可以帮助我吗?非常感谢!

谢谢

2 个答案:

答案 0 :(得分:1)

我可以看到2个问题:

  1. 可能是您的意思:
MockMvcRequestBuilders.get("/api/orders")
  1. 为了断言控制器返回了某些内容,您应该对service的调用进行存根:
@Test
public void getAllOrdersAPI() throws Exception {
   Order order = create expected order object
   when(service.findAll()).thenReturn(Arrays.asList(order));
   // rest of the test
}

答案 1 :(得分:0)

您的测试应该像这样

@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());
  }

您没有在获取URL中添加 / api 。我什么也没看到。让我知道是否有帮助,我将在您的计算机上为您编译它。

您的模拟响应为404。