现象是一个方法的结果无法正常模拟,直接进入了方法进行执行。
方法的调用是这样的
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)
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的代码看看是否有报什么异常,导致无法正常模拟。