使用mockito throw null指针异常模拟rest客户端类

时间:2014-04-01 10:14:14

标签: java junit mockito rest-client springmockito

您好我有类RestClientUtil,它与服务器执行所有与连接相关的操作,并使用rest服务获取响应。当我试图模拟我的restClientUtil成功模拟但当我尝试调用此类的方法时,方法将返回响应为null。当我在调试模式中看到restClientUtil变量时,此类的属性如pbsOrderStatusUrl {{1}因为这个原因,响应是null,所以请告诉我编写我的sellerCode的模拟方法,这是基于RestClientUtil类的响应

这是RestClientUtilClass

的方法
OrderStatusUpdate

这是我调用RestClientUtil Method

的类
 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;
    }
}

这是我试图实施的模拟测试

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

}

1 个答案:

答案 0 :(得分:1)

在行中:

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

response未初始化。

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