Ashish
Ashish

Reputation: 14707

How to mock private static inner class using Powermock

I am new to mockito+powermock. I am trying to mock a class which have private static inner class. I am facing ExceptionInInitializerError. Could someone please help me with properly initializing the class.

Error:

java.lang.ExceptionInInitializerError
    at sun.reflect.GeneratedSerializationConstructorAccessor9.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    ....................
    ....................
Caused by: java.lang.NullPointerException
    at com.ibm.retail.xpd.pos.messaging.topics.TopicComponentHelper.<init>(TopicComponentHelper.java:10)
    at com.ibm.retail.xpd.pos.messaging.topics.NodePath.<init>(NodePath.java:11)
    at com.ibm.retail.xpd.pos.messaging.service.RetailPlatformService.<init>(RetailPlatformService.java:69)
    at com.tgcs.scrt.gui.components.PageManager$PageControlService.<init>(PageManager.java:216)
    at com.tgcs.scrt.gui.components.PageManager.<clinit>(PageManager.java:242)
    ... 69 more

Class looks like:

public class PageManager{
    .........
    .........
    private static class PageControlService extends PlateFormService{
    .........
    }
}

Mocking class in test case:

PowerMockito.mockStatic( PageManager.class );

Upvotes: 1

Views: 5267

Answers (1)

user2077221
user2077221

Reputation: 934

Looks like you're missing:

Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case. Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.

from:

https://github.com/jayway/powermock/wiki/MockStatic

@Marcin - what a terrible, condescending answer. You often need to mock static classes. For example, in basho's riak client, the response class is a static inner class (which, from their POV, makes sense - only the client should be constructing responses). So if you want to mock what the client returns, you have to mock a static inner class.

Getting really tired of all the people responding to unit test questions with "don't mock X", or "that code you're testing is wrong", just because they don't know the answer.

Upvotes: 5

Related Questions