Cannot mock/spy final class using PowerMockito.spy()

亡梦爱人 提交于 2019-12-08 15:23:28

To get this working you have to understand what annotation @PrepareForTest does and make a little changes on your code:

The annotation in used to understand what class we're going to test and to prepare that class to mock static, final etc etc methods (so the methods that are not normally mockable with mockito) as normal methods.

After that you have to do this in your code:

WidgetMarshaller mockMarshaller = mock(WidgetMarshaller.class);
//Here you are doing correcly the mocking of the object

WidgetUploadClient client = new WidgetUploadClient(mockMarshaller);
//Here you have to add this line to create an object that will be spied

client = PowerMockito.spy(client);
//Here you simply spy your class

By the way there's another thing to remember, if you pass

@PrepareForTest(WidgetUploadClient.class)

to the class, you will be able to mock or spy just WidgetUploadClient class, so you have to pass two (or if you want more) parameters to the class using an array as parameter to the annotation, simply write this

@PrepareForTest({WidgetUploadClient.class, WidgetMarshaller.class})

Hope you get it working :D See you

I believe that I am using the APIs correctly but am experiencing by a bug that effects developers trying to use the combination of Robolectric and PowerMock. For reference, the bug can be tracked on Robolectric's issue tracker. The combination of libraries has been broken since at least January 2016 (currently ~6 months ago.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!