spring boot rest api测试得到404错误

Posted

技术标签:

【中文标题】spring boot rest api测试得到404错误【英文标题】:spring boot rest api test getting 404 error 【发布时间】:2019-07-18 01:21:17 【问题描述】:

我正在尝试使用 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'

任何人都可以帮助我吗?非常感谢!

谢谢

【问题讨论】:

【参考方案1】:

我可以看到 2 个问题:

    可能,您的意思是:
MockMvcRequestBuilders.get("/api/orders")
    为了断言控制器返回某些内容,您应该对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.one,但是当我执行第二个时,由于 when 和 thenReturn 方法,它会出现编译错误。 @UğurTaşkan 来自 Mockito,所以只需添加 import static org.mockito.Mockito.*; 再次感谢,现在更好了:) 响应状态更改为 401 并且我已经实现了基本安全性,正因为如此。有什么方法可以禁用此测试的安全性? @UğurTaşkan 尝试用 @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class, ManagementSecurityAutoConfiguration.class ) 注释 OrderRestControllerTest @UğurTaşkan 如果上述方法不起作用 - 请尝试 @AutoConfigureMockMvc(secure = false)【参考方案2】:

你的测试应该是这样的

@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。我没有看到其他任何东西。让我知道它是否有帮助,否则我会在我的机器上为你编译它。

你的 mockResponse 是 404。

【讨论】:

以上是关于spring boot rest api测试得到404错误的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot构建RESTful API与单元测试

Spring Boot REST API 自动化测试

Spring boot:有时没有从基于 Rest Api 的服务中得到任何响应

rest-assured : Restful API 测试利器 - 真正的黑盒单元测试(跟Spring-Boot更配哦)

Spring Boot - 使用自定义 PreAuthorize 表达式和身份验证测试 Rest Api

如何在 Spring Boot REST API 中为 db insert 方法编写模拟单元测试?