PowerMockito问题解决一则

现象是一个方法的结果无法正常模拟,直接进入了方法进行执行。

方法的调用是这样的

when(spy.checkMasterSlaveNumber(Mockito.anyList(), Mockito.anyMap())).thenReturn(appMasterSlaveArrayList);

解决思路:

经过各种尝试,均无法正常模拟,于是打断点逐步调试Powermockito的模拟代码,最终发现Powermockito执行测试代码时有报异常:ArrayList cannot be returned by toString()

在网上搜索到的解决方法是将方法调用的写法改一下

//用
	doReturn(fooBar).when(bar).getFoo()
    
//代替
	when(bar.getFoo()).thenReturn(fooBar)

https://www.codegrepper.com/code-examples/java/cannot+be+returned+by+toString%28%29+toString%28%29+should+return+String

Hi,

Well actually the issue in your code resides with the spy.
问题处在你代码中的spy上

Here is the explanation what's happening with your code.
解释下

A spy actually execute the real code by nature, so when calling "out.produce()" the expression is actually executed and return a real Product.
一个spy对象实际上会正常执行真实代码,所以你调用out.product()方法时,表达式是真时执行并且返回了一个真实的Product对象。

The constructor of Product takes the constructor arg "foo" which is a mock and it executes "f.getBar()". This invocation is recorded by mockito because this "foo" instance is a mock.
Then when you want to return "mpoo", mockito raises the exception WrongTypeOfReturnValue saying that the recorded invocation "foo.getBar()" cannot return a Product.
Product类的构造方法的构造参数 foo 是一个模拟对象,他执行了 f.getBar方法。这次调用被mockito记录了因为foo对象实例是一个模拟对象。因此当你想要返回Mpoo对象时,mockito举出WrongTypeOfReturnValue异常来标明被记录的"foo.getBar()"调用不能返回一个Product对象。


If you want to mack a partial mock, which you should avoid if possible. You need to use the following style for spies, this way mockito can tell the spy instance to only record the invocation.
如果你想要部分模拟,虽然你应该尽量避免。你应该使用以下语法,这种方式可以让spy实例只记录调用。

doReturn(mpoo).when(out).produce();

Hope that helps.


-- 
Brice

https://groups.google.com/g/mockito/c/9WUvkhZUy90

我就将我的写法改为

//原
when(spy.checkMasterSlaveNumber(Mockito.anyList(), Mockito.anyMap())).thenReturn(appMasterSlaveArrayList);
//改后
doReturn(appMasterSlaveArrayList).when(spy).checkMasterSlaveNumber(anyList, anyMap);

然后就能成功的进行测试模拟了。

Powermockito这里有个坑,就是出现它无法模拟的异常后并不会在堆栈输出,这时可以打断点进入Powermockito的代码看看是否有报什么异常,导致无法正常模拟。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值