【问题标题】:Mocking rest client class using mockito throw null pointer exception使用mockito模拟rest客户端类抛出空指针异常
【发布时间】:2014-04-01 10:14:13
【问题描述】:

嗨,我有 RestClientUtil 类,它执行与服务器的所有连接相关操作,并使用休息服务获得响应。当我尝试模拟我的 restClientUtil 成功模拟但当我尝试调用此类的方法时,该方法将返回响应为 null。当我在调试模式下看到 restClientUtil 变量时,此类的属性如 pbsOrderStatusUrl sellerCode 等即将到来null 可能是因为这个原因响应为 null 所以请告诉我如何编写我的 OrderStatusUpdate 的 mockito,它基于 RestClientUtil 类的响应

这是RestClientUtilClass的方法

 public class RestClientUtil{
       @Value("#{externalProperties['PBSUrl']}")
      private String pbsUrl;

    @Value("#{externalProperties['PBSOrderStatusUrl']}")
    private String pbsOrderStatusUrl;

    @Value("#{externalProperties['sellerCode']}")
    private String sellerCode;

    @Value("#{externalProperties['PAYMENT_CLIENT_URL']}")
    private String paymentClientURL;

    @Value("#{externalProperties['PBS_COMMUNICATION_URL']}")
    private String pbsCommunicationURL;

    private WebResource webResource;    

public com.mycompany.wrapper.orderstatusupdate.resp.Response orderStatusUpdateToProvider(
            com.mycompany.wrapper.orderstatusupdate.req.Request req, String specificURL)
            throws EcomGenericException {
        com.mycompany.wrapper.orderstatusupdate.resp.Response response = null;
        int i = 0;
        for (; i < 3; i++) {
//pbsUrl is some UrlTo differntServer
            try {
                Client client = Client.create();
                WebResource webResource = client.resource(UriBuilder.fromUri(
                        pbsUrl).build());
                log.debug("Input to the PBS system for orderStatusUpdateToProvider ==> "
                        + req);
                MultivaluedMap queryParams = new MultivaluedMapImpl();
                queryParams.add("sellerCode", sellerCode);
                response = webResource.path("seller").path("orders")
                        .path(specificURL).queryParams(queryParams)
                        .header("correlationId", req.getCorrelationId())
                        .type(MediaType.APPLICATION_XML)
                        .post(com.mycompany.wrapper.orderstatusupdate.resp.Response.class,
                                req);
                log.trace("response ==> " + response);
                if (null == response) {
                    log.error("Order Update Status  is null");
                    throw new EcomGenericException("validation_500");
                }
                break;
            } catch (UniformInterfaceException e) {

            }
        }

        return response;
    }
}

这是我调用 RestClientUtil 方法的类

     @Service
    public class OrderStatusUpdate {

        private static final Logger logger = Logger
                .getLogger(OrderStatusUpdate.class);
        @Resource(name = "restClientUtil")
        protected RestClientUtil restClientUtil;

        @Resource(name = "blOrderService")
        protected OrderService orderService;
        public void setRestClientUtil(RestClientUtil restClientUtil) {
            this.restClientUtil = restClientUtil;
        }

        public void setOrderService(OrderService orderService) {
            this.orderService = orderService;
        }


        public void orderStatusUpdate(Order order, String providerStatus, String targetStatus,
                String dateTime, String targetURI) throws EcomGenericException,  org.broadleafcommerce.core.pricing.service.exception.PricingException {

            Request request = new ObjectFactory()
                    .createRequest();
            Request.Order orderReq = new Request.Order();
            orderReq.setOrderId(order.getOrderNumber());
            orderReq.setStatus(providerStatus);
            orderReq.setDateTime(dateTime);
            request.setOrder(orderReq);
            request.setCorrelationId(UUID.randomUUID().toString());
            com.mycompany.wrapper.orderstatusupdate.resp.Response response = restClientUtil.orderStatusUpdateToProvider(request,targetURI);
            if (response != null && ApplicationConstants.PROVIDER_SUCCESS_IDENTIFIER.equals(response.getStatus().getCode())) {
                order.setStatus(CustomOrderStatus.getInstance(targetStatus));
                orderService.save(order, false);
            } else {
logger.error("OrderStatusUpdate call failed from the Provider end for ECOM OrderID " +order.getId()+ " with ErrorCode "+ response.getStatus().getCode() + " with Error message "+ response.getStatus().getMessage());
            throw new EcomGenericException("validation_500");
            }
        }

    }

这是我尝试实现的模拟测试

  public class OrderStatusUpdateTest {

    protected RestClientUtil restClientUtil;

    protected OrderService orderService;

    protected OrderStatusUpdate orderStatusUpdate;
    protected Request request;
    private Response response;
    private Order blcOrder;
    private com.mycompany.account.CustomOrderStatus CustomOrderStatus;

    @Before
    public void setUp() {
     restClientUtil=mock(RestClientUtil.class);
     orderService=mock(OrderService.class);
     blcOrder=new OrderImpl();
     request=new Request();
     blcOrder.setStatus(CustomOrderStatus.PAYMENT_COMPLETED);
     orderStatusUpdate=new OrderStatusUpdate();
     orderStatusUpdate.setOrderService(orderService);
     orderStatusUpdate.setRestClientUtil(restClientUtil);
     Request.Order order=new Request.Order();
     order.setOrderId("123455");
     order.setStatus("PAYMENT COMPLETED");
     order.setDateTime("2013-11-21T09:30:47+0500");
     request.setCorrelationId("12343");
     request.setOrder(order);

     when(restClientUtil.orderStatusUpdateToProvider(request, "http://localhost:8080/")).thenReturn(response);
    }

    @Test
    public void test() throws PricingException {

        orderStatusUpdate.orderStatusUpdate(blcOrder, "PAYMENT COMPLETED","IN_PAYMENT", "2013-11-21T09:30:47+0500", "http://localhost:8080/");
        verify(restClientUtil.orderStatusUpdateToProvider(request, "http://localhost:8080/"));
        verify(orderService.save(blcOrder, false));

        fail("Not yet implemented");
    }

}

这是错误日志

 java.lang.NullPointerException
    at com.mycompany.api.service.orderstatusupdate.OrderStatusUpdate.orderStatusUpdate(OrderStatusUpdate.java:72)
    at com.mycompany.api.service.orderstatusupdate.test.OrderStatusUpdateTest.test(OrderStatusUpdateTest.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

【问题讨论】:

  • 你能用// exception here 或类似的方式突出显示OrderStatusUpdate 类中的第72 行吗?
  • @Duncan 你可以在 OrderStatusUpdate 类方法中看到记录器 orderStatusUpdate(....) 这是 72 行,因为这里使用了响应
  • @Duncan FYI 类级别变量用于 RestCLientUtil 类通过属性文件实时填充
  • response 在测试用例中未初始化,并在调用 orderStatusUpdateToProvider 时返回。在 logger 中,您正在尝试从 null 对象中读取状态代码。
  • @Duncan 我可以删除记录器没问题,但我需要回复为什么它即将到来的 null 你能帮我解决这个问题

标签: java junit mockito rest-client springmockito


【解决方案1】:

行内:

when(restClientUtil.orderStatusUpdateToProvider(request,"http://localhost:8080")).thenReturn(response);

response 未初始化。

orderStatusUpdate 方法中的if-else 条件不正确,因为如果responsenull,记录器仍会尝试从中访问状态码。

【讨论】:

  • 我将删除记录器,但响应仍然为 null 我需要响应来测试我的功能功能我如何得到它?
  • @henrycharles 在您的测试中,您需要构造您的response 对象。 IE。 response = new Response();,或类似的。
  • @Duncan 我将创建响应对象没问题,但是在我的 restClientUtil 类中,它将转到 orderStatusUpdateToProvider 方法,我遇到了问题,因为这需要 pbsURL SellerCode 和更多参数,然后调用 post 方法获取响应。实时我正在使用不同的服务来获取响应,这些响应在不同的机器上可用,他们期望 webResource 中有如此庞大的参数列表,然后他们正在发送响应现在的问题是我如何模拟这种行为以在我的OrderStatusUpdate 类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
相关资源
最近更新 更多