简体   繁体   中英

Avoiding cast in bytecode on list elements with Powermockito 1.5

I use powermock with mockito because I need its static method mocking feature.
I am trying to upgrade Powermock from 1.4.9 to 1.5.6 and mockito from 1.9 to 1.9.5 because PowerMockRunner in 1.4.9 breaks unexpectedly under particular condition in my IDE and the problem is solved in 1.5 version which in turn needs the latter to be upgraded.
When I define the following in my unit test

when(cart.getProducts().get(0)).thenReturn(productMock);

a ClassCastException is raised from Stub type to actual list element type. cart is a deep stub mock.
Decompiling the byte code, I notice that it tries to cast as in example below

org/mockito/Mockito.when((com/shop/Product)cart.getProducts().get(0))
                   .thenReturn(productMock);

When decompiling the same code compiled with Powermock 1.4.12 I get

org/mockito/Mockito.when(cart.getProducts().get(0))
                   .thenReturn(productMock);

There is no attempt to cast get(0) result.
It breaks lot of my unit tests and I would like to know if there is any way to avoid that.

You must do it in 2 steps:

List<Product> products  = new ArrayList<>();
// add your product here with products.add()

when(cart.getProducts()).thenReturn(products);

You can also mock the ArrayList but that's not necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM