Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java spring引导rest api测试获取404错误_Java_Rest_Spring Boot_Testing_Junit - Fatal编程技术网

Java spring引导rest api测试获取404错误

Java spring引导rest api测试获取404错误,java,rest,spring-boot,testing,junit,Java,Rest,Spring Boot,Testing,Junit,我试图用RESTAPI创建一个基本的spring引导应用程序(JDK1.8)。下面是我的申请代码 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OrderApplication { public s

我试图用RESTAPI创建一个基本的spring引导应用程序(JDK1.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 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();
    }


}
import java.util.List;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Service;
@服务
公共类OrderServiceImpl实现OrderService{
私有OrderDAO OrderDAO;
//注入顺序dao{使用构造函数注入}
@自动连线
公共OrderServiceImpl(OrderDAO或OrderDAO){
orderDao=theOrderDao;
}
@凌驾
公共列表findAll(){
返回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'
HTTP方法=GET
请求URI=/orders
参数={}
Headers=[Accept:“application/json”]
正文=
会话属性={}
处理程序:
Type=org.springframework.web.servlet.resource.ResourceHttpRequestHandler
异步:
异步启动=错误
异步结果=空
已解决的异常:
类型=空
ModelAndView:
视图名称=空
视图=空
模型=空
FlashMap:
属性=空
MockHttpServletResponse:
状态=404
错误消息=null
Headers=[X-Content-Type-Options:“nosniff”,X-XSS-Protection:“1;mode=block”,缓存控制:“无缓存,无存储,最大年龄=0,必须重新验证”,Pragma:“无缓存”,Expires:“0”,X-Frame-Options:“拒绝”]
内容类型=空
正文=
转发的URL=null
重定向的URL=null
Cookies=[]
2019-02-24 14:55:56.623信息276---[Thread-3]o.s.s.concurrent.ThreadPoolTaskExecutor:正在关闭ExecutorService'applicationTaskExecutor'
有人能帮我吗?非常感谢


谢谢你的测试应该是这样的

@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());
  }
您没有在get URL中添加/api。我看不到其他任何东西。让我知道如果它有帮助的话,我会去我的机器上为你编译它

您的模拟响应是404。

我可以看到两个问题:

  • 也许,你的意思是:
  • MockMvcRequestBuilders.get(“/api/orders”)
    
  • 为了断言控制器返回某些内容,您应该对
    服务进行存根调用
  • @测试
    public void getAllOrdersAPI()引发异常{
    订单=创建预期的订单对象
    when(service.findAll()).thenReturn(Arrays.asList(order));
    //剩下的测试
    }
    
    谢谢,我实现了1.one,但对于第二个,当我实现时,由于when和thenReturn方法,它会出现编译错误。@UğurTaşkan它来自Mockito,所以只需添加
    导入静态org.Mockito.Mockito.*再次感谢,现在更好了:)响应状态更改为401,我已经实现了基本的安全性,这就是原因。有什么方法可以禁用此测试的安全性吗?@UğurTaşkan尝试用
    @EnableAutoConfiguration(exclude={SecurityAutoConfiguration.class,ManagementSecurityAutoConfiguration.class})注释
    OrderRestControllerTest
    类,如果上述方法不起作用-尝试
    @autoconfiguragemockmvc(secure=false)
    @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());
      }