Search code examples
javamockingpowermockito

How to mock static call of a private static method in initialization of the class with (Power)Mockito?


I have a weird situation which is consequence of some poor design, but its a fact I need to accept. The problem is that it makes me problems when mocking because problematic method is having side effects when trying to find some local file which is not existent at the build machine.

It is something like this:

class BadDesignedClass {
    public static final Properies = loadProperties();
    private static Properties loadProperties() {
        // ... loads non-existent property file and crashes...
    }
}

I have problem to mock this because at the moment I mention the class inside the test class it calls real loadProperties() which is before Mockito or PowerMockito do any mocking, which results an error thrown.


Solution

  • To have the complete solution, I'll show here what I did exactly, inspired by SpaceTrucker's advice:

    First: load the class without the initialization:

    Class<?> clazz = Thread.currentThread().getContextClassLoader()
            .loadClass("org.example.BadDesignedClass");
    

    Second: suppress the static method which was making all the problems.

    PowerMockito.suppress(PowerMockito.method(clazz , "loadProperties"));
    

    Third: Continue to mock the class as usual, since loadProperties() is suppressed now.

    PowerMockito.mockStatic(BadDesignedClass.class);
    PowerMockito.when(BadDesignedClass.someMethod()).thenReturn("something");