今天使用PowerMock进行单元测试,
系统环境
系统框架: Spring+Spring MVC+MyBatis
构建工具: Maven
所需依赖
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.7.1</version> <exclusions> <exclusion> <groupId>org.junit</groupId> <artifactId>junit</artifactId> </exclusion> <exclusion> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> </exclusion> <exclusion> <groupId>org.powermock</groupId> <artifactId>powermock-reflect</artifactId> </exclusion> </exclusions> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.7.1</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
注解说明
@RunWith 用于指定PowerMockRunner作为Junit的runner。
@PrepareForTest 在Mock静态、final、私有方法 时需要使用
测试示例
普通Mock: Mock参数传递的对象
待测试方法
public class FlySunDemo { public boolean callArgumentInstance(File file) { return file.exists(); } }
测试case:
@RunWith(PowerMockRunner.class) public class FlySunDemoTest { @Test public void callArgumentInstance() { File file = PowerMockito.mock(File.class); FlySunDemo flySunDemo = new FlySunDemo(); PowerMockito.when(file.exists()).thenReturn(true); Assert.assertTrue(flySunDemo.callArgumentInstance(file)); } }
说明:PowerMockito.when().thenReturn()用于为mock对象的方法指定返回值。如果
2. Mock方法内部new出来的对象,对于这种我们需要在类上添加@PrepareForTest注解。如果没有显示的指定方法行为,mock对象的方法调用就会根据powermock的具体配置执行默认行为。而不会调用真实方法。
待测试方法
public boolean callArgumentInstance2(String path) { File file = new File(path); return file.exists(); }
测试方法
@PrepareForTest(FlySunDemo.class) @Test public void callArgumentInstance2() { File file = PowerMockito.mock(File.class); try { PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file); FlySunDemo flySunDemo = new FlySunDemo(); PowerMockito.when(file.exists()).thenReturn(true); Assert.assertTrue(flySunDemo.callArgumentInstance2("bbb")); } catch (Exception e) { e.printStackTrace(); } }
Mock普通对象的静态方法
待测试方法
/** * Mock普通对象的静态方法 * @return */ public boolean callStaticMethod() { return ClassDependency.isStaticAlive(); }
/** * @author xiang.wei * @create 2018/7/5 14:19 */ public class ClassDependency { public final boolean isFinalAlive() { return false; } public static boolean isStaticAlive() { return false; } }
测试case
@Test @PrepareForTest(ClassDependency.class) public void testCallStaticMethod() { PowerMockito.mockStatic(ClassDependency.class); PowerMockito.when(ClassDependency.isStaticAlive()).thenReturn(true); FlySunDemo flySunDemo = new FlySunDemo(); Assert.assertTrue(flySunDemo.callStaticMethod()); }
在Mock Static method的时候,含静态方法的类需要写到@PrepareForTest注解里面
4. Mock普通对象的final方法
public boolean callFinalMethod(ClassDependency refer) { return refer.isFinalAlive(); }
@Test @PrepareForTest(ClassDependency.class) public void testCallFinalMethod() { ClassDependency refer = PowerMockito.mock(ClassDependency.class); PowerMockito.when(refer.isFinalAlive()).thenReturn(false); FlySunDemo flySunDemo = new FlySunDemo(); Assert.assertFalse(flySunDemo.callFinalMethod(refer)); }
mock 私有方法
/** * mock 私有方法 * @return */ public boolean callPrivateMethod() { return isAlive(); } private boolean isAlive() { return false; }
@Test @PrepareForTest(FlySunDemo.class) public void callPrivateMethod() throws Exception { FlySunDemo demo = PowerMockito.mock(FlySunDemo.class); PowerMockito.when(demo.callPrivateMethod()).thenCallRealMethod(); PowerMockito.when(demo, "isAlive").thenReturn(true); Assert.assertTrue(demo.callPrivateMethod()); }
Mock系统类的静态和final方法
/** * Mock系统类的静态和final方法 * @param string * @return */ public String callSystemStaticMethod(String string) { return System.getProperty(string); }
@Test @PrepareForTest(FlySunDemo.class) public void testCallSystemStaticMethod() { FlySunDemo flySunDemo = new FlySunDemo(); PowerMockito.mockStatic(System.class); PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb"); Assert.assertEquals("bbb",flySunDemo.callSystemStaticMethod("aaa")); }
参考
https://blog.csdn.net/hotdust/article/details/53406044
————————————————–分割线——————————————————————————-
PowerMock 与Spring 的整合
通过@InjectMocks mock 出待测试类的实例
例如:
实际类
@Service("NotifyPayService") public class NotifyPayServiceImpl implements NotifyPayService {...}
测试case
@InjectMocks private NotifyPayService notifyPayService = new NotifyPayServiceImpl();
通过@Mock mock 出注入的类。
例如:
实际类
@Autowired private MallOrderService mallOrderService;
测试case
@Mock private MallOrderService mallOrderService;
测试实战:
@Override public void notifyay(HttpServletRequest request, HttpServletResponse response) throws IOException { String xml = request.getParameter("xml"); logger.info("收到支付平台异步通知:xml={}" , xml); // 异步通知解析处理 Document document = null; try { document = DocumentHelper.parseText(xml); } catch (DocumentException e) { logger.error("异步通知xml解析失败:xml={}" , xml); return; } Element root = document.getRootElement(); Element pubInfo = root.element(CommonNode.PUBINFO); Element busiData = root.element(CommonNode.BUSIDATA); String transactionId = pubInfo.elementTextTrim(CommonNode.TRANSACTIONID); String verifyCode = pubInfo.elementTextTrim(CommonNode.VERIFYCODE); String busiDataStr = XMLUtil.xmlToString(xml); if(busiDataStr == null){ logger.error("异步通知busiData转为字符串出错:busiData={}" , busiData); } String signData = transactionId + busiDataStr; //获取支付平台分配的MD5Key Long orderid = Long.valueOf(busiData.elementTextTrim(CommonNode.ORDERID)); boolean singleOrder = true; List<MallOrder> cartOrders = new ArrayList<>(); MallOrder order = mallOrderService.selectByOrderId(orderid); if(order == null){ List<Long> orderids = orderParentMapper.selectByorderidParent(orderid); for (Long tOrderid : orderids) { MallOrder cartOrder = mallOrderService.selectByOrderId(tOrderid); cartOrders.add(cartOrder); } } if(cartOrders.size() > 0){ singleOrder = false; } logger.info("查询订单状态"); if ( singleOrder && (order == null || order.getPlatformid()==null)) { logger.error("数据库未找到该记录或订单平台号不存在,订单号={}" , orderid); return; } if(!singleOrder && cartOrders.isEmpty()){ logger.error("数据库未找到该记录,订单号={}" , orderid); return; } Long platformId; if(singleOrder){ platformId = order.getPlatformid(); }else { platformId = cartOrders.get(0).getPlatformid(); } String md5Key = mallPlatformMapper.selectKeyByPlatformId(platformId); boolean verfiyFlag = MD5.verify(signData, verifyCode, md5Key, "utf-8"); logger.info("异步通知验签:待签名字符串={}",signData); if (!verfiyFlag) { logger.error("异步通知验签失败:xml={}" , xml); return; } //告诉支付平台,已收到通知 logger.info("异步通知返回验签结果"); response.getWriter().println("success"); response.getWriter().flush(); logger.info("查询订单状态"); if (!OrderType.WAIT.getCode().equals(singleOrder ? order.getOrdertype() : cartOrders.get(0).getOrdertype()) && !OrderType.CANCEL.getCode().equals(singleOrder ? order.getOrdertype() : cartOrders.get(0).getOrdertype())) { logger.error("收到重复异步通知,该订单已更新为成功状态,订单号={}" , orderid); return; } Integer price = Integer.valueOf(AmountUtil.formatYuan2Fen(busiData .elementTextTrim(CommonNode.PAYAMOUNT))); //对比订单金额,不一致输出错误日志,第三方支付金额+虚拟币金额(暂时只有和米) //对比订单金额,如果不一致,说明有被篡改风险,则不更新支付状态 Integer realPayPrice = 0; Integer virtualPrice = 0; if(singleOrder){ realPayPrice = order.getPrice(); if(order.getHemiprice()!= null && order.getHemiprice()>0){ virtualPrice = order.getHemiprice(); } }else { for (MallOrder cartOrder : cartOrders) { realPayPrice += cartOrder.getPrice(); if(cartOrder.getHemiprice()!= null && cartOrder.getHemiprice()>0){ virtualPrice += cartOrder.getHemiprice(); } } } Integer totalPrice = realPayPrice + virtualPrice * 100; if (!price.equals(totalPrice)) { logger.error("警告:该笔支付通知金额与实际金额不符,订单号={}" , orderid); logger.error("订单金额不符,订单金额={},虚拟币(和米)金额={},支付返回={}",realPayPrice,virtualPrice,price); return; } Integer ordertype = Integer.valueOf(busiData.elementTextTrim(CommonNode.STATUS)); String failureReasons = busiData.elementTextTrim(CommonNode.STATUSINFO); String tradeNo = busiData.elementTextTrim(CommonNode.DONECODE); String payTypeStr = busiData.elementTextTrim(CommonNode.TYPE); Date payTime = null; try { String payDateString = busiData.elementTextTrim(CommonNode.PAYDATE); if (StringUtils.isNotEmpty(payDateString)) { payTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(busiData .elementTextTrim(CommonNode.PAYDATE)); } } catch (ParseException e) { logger.error("支付时间解析失败:payDate={}" , busiData.elementTextTrim(CommonNode.PAYDATE)); } //支付方式 int payType = 0; switch(payTypeStr){ case "cmpay" : payType = 1; break; //和包 case "alipay" : payType = 2; break; //支付宝 case "wechatpay" : payType = 4; break; //微信 case "unionpay" : payType = 5; break; //银联 case "gscmpay" : payType = 8; break; //和包陕西平台 case "IntegralPay" : payType = 15; break; // 积分支付 case "MergePay" : payType = 16; break; // 组合支付 case "hemipay" : payType = 17; break; // 和米支付 default : payType = 0; } Map map = new HashMap(); map.put("orderid",orderid); map.put("ordertype",ordertype); map.put("failureReasons",failureReasons); map.put("tradeNo",tradeNo); map.put("payTime",payTime); map.put("payType",payType); //对订单进行处理,包括订单状态、更新库存、发货、流量币、限购…… if(singleOrder){ orderHandle(order,map); }else { for (MallOrder cartOrder : cartOrders) { //替换成mall_order订单号 map.put("orderid",cartOrder.getOrderid()); orderHandle(cartOrder,map); } } }
@RunWith(PowerMockRunner.class) @PrepareForTest( { HttpUtil.class }) @PowerMockIgnore("javax.net.ssl.*") public class NotifyPayServiceTest { @InjectMocks private NotifyPayService notifyPayService = new NotifyPayServiceImpl(); @Mock private MallOrderService mallOrderService; @Mock private MallProductService mallProductService; @Mock private MallCatalogService mallCatalogService; @Mock private MallUserService mallService; @Mock private MallAddressService mallAddressService; @Mock private CouponService couponService; @Mock private HemiService hemiService; @Mock private SiteConfig siteConfig; @Mock private CacheService redisService; @Mock private MallPlatformMapper mallPlatformMapper; @Mock private OrderParentMapper orderParentMapper; @Mock private OrderSonMapper orderSonMapper; @Mock private MallOrderMapper mallOrderMapper; @Mock private MallMerchantService mallMerchantService; @Mock private WangyiYanxuanService wangyiYanxuanService; /** * setUp */ @Before public void setUp(){ MockitoAnnotations.initMocks(this); } @Test public void testNotifyay1() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); String xml; // 异步通知xml解析失败:xml={} xml = ""; when( mallOrderService.selectByOrderId(any())).thenReturn(order); orderids.add(123L); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 数据库未找到该记录或订单平台号不存在,订单号={} xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>123</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId></BusiData></request>"; when( mallOrderService.selectByOrderId(any())).thenReturn(order); orderids.add(123L); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test public void testNotifyay2() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); String xml; // 异步通知验签失败 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>123</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId></BusiData></request>"; order.setPlatformid(1234L); when( mallOrderService.selectByOrderId(any())).thenReturn(order); //orderids.clear(); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test public void testNotifyay3() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); String xml; // 收到重复异步通知,该订单已更新为成功状态,订单号={} xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>2ce649905197af9a4636ac5351b81284</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.SUCCESS.getCode()); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test public void testNotifyay4() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); String xml; // 订单金额不符,订单金额={},虚拟币(和米)金额={},支付返回={} xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>1505bc92aa677a5482068cb977744887</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>1</PayAmount></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1); order.setHemiprice(1); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test public void testNotifyay5() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); String xml; // 0 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>2a73eef51f4dd371e92f32b8f8c2552c</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>1</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 和包 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>8a145d79c9cc72eb8aa4e5cdc01c8268</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>cmpay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 支付宝 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>c0df2c3a1eb578cab46ff52cf3d5ac55</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>alipay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 微信 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>17602611d27e06ca62eee4604b71c07a</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>wechatpay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 银联 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>80e5c0d7ab716ddba5863b820bb4fd5b</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>unionpay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 和包陕西平台 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>c13f233a677dfcf3781f7f47e74ed267</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>gscmpay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 积分支付 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>f68d51e8a09067a998b260caa84a9c88</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>IntegralPay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 组合支付 xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>c363a69669384e6928e71d8413a40a7d</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>MergePay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // 和米支付->该订单支付未成功,支付订单号trade_no={} xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>dcc8398bc50deaf7dcf6f4dba84ea908</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>1</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>hemipay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test @PrepareForTest(HttpUtil.class) public void testNotifyay6() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); MallAddress address = new MallAddress(); MallProduct product = new MallProduct(); MallMerchant mallMerchant = new MallMerchant(); MallCatalog catalog = new MallCatalog(); JsonResult result = new JsonResult(); MallUser user = new MallUser(); String xml; // orderHandle:普通订单->该订单对应的商品不存在,订单号={} xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>0c93bdf8e80e7b90a06e953e46711bcf</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>0</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>1</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); order.setCartType(CartType.SINGLE.getType()); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); address.setReceiverPhone("12346"); when( mallAddressService.selectAddressByIds(any(),any(),any())).thenReturn(address); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // orderHandle:普通订单->orderHandleByProduct xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>0c93bdf8e80e7b90a06e953e46711bcf</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>0</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>1</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1001L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); order.setCartType(CartType.SINGLE.getType()); order.setUserId(1245L); order.setCount(1000); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); catalog.setCatalogName(Constant.CATALOGTYPE.CATALOGFORMIGU); when( mallCatalogService.getByCatalogId(any())).thenReturn(catalog); address.setReceiverPhone("12346"); when( mallAddressService.selectAddressByIds(any(),any(),any())).thenReturn(address); product.setNumLimit(1); when( mallProductService.selectProductByIdTime(any(),any())).thenReturn(product); when( mallProductService.updateCount(any())).thenReturn(1); when( redisService.getObj(any(),any())).thenReturn(1); mallMerchant.setSupplierid(5L); when( mallMerchantService.getMerchantById(any())).thenReturn(mallMerchant); result.setCode(WangyiResponseCode.SUCCESS); when( wangyiYanxuanService.orderCreate(any())).thenReturn(result); when( mallOrderMapper.updateByPrimaryKeySelective(any())).thenReturn(1); when( siteConfig.getCouponPointBegin()).thenReturn("2015-01-01 00:00:00"); when( siteConfig.getCouponPointEnd()).thenReturn("2095-01-01 00:00:00"); when( redisService.getObj(any(),any())).thenReturn(null); user.setPassId("123456"); when( mallService.select(any(),any())).thenReturn(user); PowerMockito.mockStatic(HttpUtil.class); HttpUtil httpUtilMock = PowerMockito.mock(HttpUtil.class); PowerMockito.when(HttpUtil.getInstance()).thenReturn(httpUtilMock); PowerMockito.when(httpUtilMock.sendByJson(any(), any())).thenReturn("{\"ROOT\":{\"BODY\":{\"RETURN_CODE\":\"0\",\"OUT_DATA\":{\"PAYSN\":\"1\",\"CREATE_TIME\":\"20150101000000\"}}}}"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test @PrepareForTest(HttpUtil.class) public void testNotifyay7() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); MallAddress address = new MallAddress(); MallProduct product = new MallProduct(); MallMerchant m = new MallMerchant(); MallCatalog catalog = new MallCatalog(); JsonResult result = new JsonResult(); MallUser user = new MallUser(); String xml; // orderHandle:普通订单->orderHandleByProduct xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>f93d0739da1cf5266e61f1dbd201e554</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>0</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>hemipay</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1002L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); order.setCartType(CartType.SINGLE.getType()); order.setUserId(1245L); order.setCount(1000); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); catalog.setCatalogName(Constant.CATALOGTYPE.CATALOGFORMIGU); when( mallCatalogService.getByCatalogId(any())).thenReturn(catalog); when( hemiService.miguCoinExchange(any())).thenReturn(true); address.setReceiverPhone("12346"); when( mallAddressService.selectAddressByIds(any(),any(),any())).thenReturn(address); product.setNumLimit(1); when( mallProductService.selectProductByIdTime(any(),any())).thenReturn(product); when( mallProductService.updateCount(any())).thenReturn(1); when( redisService.getObj(any(),any())).thenReturn(1); m.setSupplierid(5L); when( mallMerchantService.getMerchantById(any())).thenReturn(m); result.setCode(WangyiResponseCode.SUCCESS); when( wangyiYanxuanService.orderCreate(any())).thenReturn(result); when( mallOrderMapper.updateByPrimaryKeySelective(any())).thenReturn(1); when( siteConfig.getCouponPointBegin()).thenReturn("2015-01-01 00:00:00"); when( siteConfig.getCouponPointEnd()).thenReturn("2095-01-01 00:00:00"); when( redisService.getObj(any(),any())).thenReturn(null); user.setPassId("123456"); when( mallService.select(any(),any())).thenReturn(user); PowerMockito.mockStatic(HttpUtil.class); HttpUtil httpUtilMock = PowerMockito.mock(HttpUtil.class); PowerMockito.when(HttpUtil.getInstance()).thenReturn(httpUtilMock); PowerMockito.when(httpUtilMock.sendByJson(any(), any())).thenReturn("{\"ROOT\":{\"BODY\":{\"RETURN_CODE\":\"0\",\"OUT_DATA\":{\"PAYSN\":\"1\",\"CREATE_TIME\":\"20150101000000\"}}}}"); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } @Test @PrepareForTest(HttpUtil.class) public void testNotifyay8() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletRequest request = new MockHttpServletRequest(); MallOrder order = new MallOrder(); List<Long> orderids = new ArrayList<Long>(); MallAddress address = new MallAddress(); MallProduct product = new MallProduct(); MallMerchant m = new MallMerchant(); MallCatalog catalog = new MallCatalog(); JsonResult result = new JsonResult(); MallUser user = new MallUser(); List<OrderSon> orderSons = new ArrayList<OrderSon>(); OrderSon son = new OrderSon(); String xml; // orderHandle:购物车订单->该订单对应的商品不存在,订单号={},产品id={} xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>0c93bdf8e80e7b90a06e953e46711bcf</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>0</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>1</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); order.setCartType(CartType.CART.getType()); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); address.setReceiverPhone("12346"); when( mallAddressService.selectAddressByIds(any(),any(),any())).thenReturn(address); son.setProductId(124L); orderSons.add(son); when( orderSonMapper.selectByOrderid(any())).thenReturn(orderSons); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); // orderHandle:购物车订单->orderHandleByProduct xml = "<request><PubInfo><TransactionId>12345</TransactionId><VerifyCode>0c93bdf8e80e7b90a06e953e46711bcf</VerifyCode></PubInfo><BusiData><OrderId>12345678</OrderId><PayAmount>10</PayAmount><Status>0</Status><StatusInfo>abc</StatusInfo><DoneCode>123</DoneCode><Type>1</Type><PayDate>2015010100000000</PayDate></BusiData></request>"; order.setPlatformid(1234L); order.setOrdertype(OrderType.FAIL.getCode()); order.setPrice(1000); order.setHemiprice(0); order.setCartType(CartType.CART.getType()); when( mallOrderService.selectByOrderId(any())).thenReturn(order); when( orderParentMapper.selectByorderidParent(any())).thenReturn(orderids); when( mallPlatformMapper.selectKeyByPlatformId(any())).thenReturn("1234567890"); address.setReceiverPhone("12346"); when( mallAddressService.selectAddressByIds(any(),any(),any())).thenReturn(address); son.setProductId(124L); orderSons.add(son); when( orderSonMapper.selectByOrderid(any())).thenReturn(orderSons); product.setNumLimit(1); when( mallProductService.selectProductByIdTime(any(),any())).thenReturn(product); m.setSupplierid(5L); when( mallMerchantService.getMerchantById(any())).thenReturn(m); result.setCode(WangyiResponseCode.SUCCESS); when( wangyiYanxuanService.orderCreate(any())).thenReturn(result); when( mallOrderMapper.updateByPrimaryKeySelective(any())).thenReturn(1); when( siteConfig.getCouponPointBegin()).thenReturn("2015-01-01 00:00:00"); when( siteConfig.getCouponPointEnd()).thenReturn("2095-01-01 00:00:00"); when( redisService.getObj(any(),any())).thenReturn(null); user.setPassId("123456"); when( mallService.select(any(),any())).thenReturn(user); PowerMockito.mockStatic(HttpUtil.class); HttpUtil httpUtilMock = PowerMockito.mock(HttpUtil.class); PowerMockito.when(HttpUtil.getInstance()).thenReturn(httpUtilMock); PowerMockito.when(httpUtilMock.sendByJson(any(), any())).thenReturn("{\"ROOT\":{\"BODY\":{\"RETURN_CODE\":\"0\",\"OUT_DATA\":{\"PAYSN\":\"1\",\"CREATE_TIME\":\"20150101000000\"}}}}"); request.setParameter("xml", xml); request.setParameter("xml", xml); notifyPayService.notifyay(request, response); } }