java - spring boot rest api测试出现404错误

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

我添加了一个 Controller 如下

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 个问题:

  1. 您的意思可能是:
MockMvcRequestBuilders.get("/api/orders")
  1. 为了断言 Controller 返回某些东西,您应该 stub 调用服务:
@Test
public void getAllOrdersAPI() throws Exception {
   Order order = create expected order object
   when(service.findAll()).thenReturn(Arrays.asList(order));
   // rest of the test
}

关于java - spring boot rest api测试出现404错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54852641/

相关文章:

spring - @Valid 不适用于 spring 中 bean 类中的嵌套对象

javascript - Apigee 路由帖子获取 api

python - API 和 API 库/包装器之间的区别

java - 在 spring-boot 中监听存储库事件

node.js - 如何在服务器上创建流端点?

java - jetty 和 Jersey : How does everything fits together?

spring-boot - 如何从密码 hashcorpVault 动态读取 liquibase.properties

java - jackson YAML : mapping a regex Pattern with flags

java - Spring 4 网络 - java.lang.IllegalArgumentException : No matching constant for [0]

java - CrudRepository 和 hibernate : save(List<S>) vs save(Entity) in transaction