无法使用PowerMock模拟构造函数

编程入门 行业动态 更新时间:2024-10-26 16:22:38
本文介绍了无法使用PowerMock模拟构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在下面的代码中,我无法使用PowerMock模拟构造函数. 我想在下面的语句中打勾.

Here in below code i am not able to Mock Constructor using PowerMock. I want to MOck below statement.

APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);

下面是我的模拟步骤

@PrepareForTest({APSPPortletRequest.class}) @RunWith(PowerMockRunner.class) public class ReminderPortletControllerTest { private PortletRequest requestMock; private APSPPortletRequest apspPortletRequestMock; public void setUp() throws Exception { requestMock = EasyMock.createNiceMock(PortletRequest.class); apspPortletRequestMock = EasyMock.createNiceMock(APSPPortletRequest.class); } @Test public void testExecuteMethod() throws Exception { PowerMock.expectNew(APSPPortletRequest.class, requestMock).andReturn(apspPortletRequestMock).anyTimes(); EasyMock.replay(apspPortletRequestMock, requestMock); PowerMock.replayAll(); } }

请在那方面建议我.

推荐答案

要模拟这一行

APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);

此对象创建调用仅使用一个参数,但是在测试方法中进行模拟时,您要将两个值传递给expectNew方法.

this object creation call takes only one parameter,but while mocking in your test method you are passing two values to expectNew method.

实际上您应该这样做

PowerMock.expectNew(APSPPortletRequest.class, EasyMock.anyObject(requestClass.class)).andReturn(apspPortletRequestMock).anyTimes();

这样做是告诉编译器,只要在类APSPPortletRequest上以请求类的任何对象作为参数调用"new"运算符,就返回一个模拟实例apspPortletRequestMock.

by doing this you are telling compiler to return a mocked instance apspPortletRequestMock whenever 'new' operator is called on class APSPPortletRequest with any object of request class as parameter.

您还缺少一点,您也需要重播所有Easymock对象.即EasyMock.replay(...);也需要存在.

and you are also missing a small point you need to replay all the Easymock objects too.. i.e. EasyMock.replay(...); also needs to be present.

希望这会有所帮助!

祝你好运!

更多推荐

无法使用PowerMock模拟构造函数

本文发布于:2023-10-31 05:45:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   PowerMock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!