Junit Rule with PowerMockito : ClassNotPreparedException

168 Views Asked by At

I working on testing some static classes using PowerMockito, and sometimes the test fail, in order to overcame this issue a create a customize JUnit Rule to re-run the failure tests. The rule works fine but whenever the test is re-executed , it's fail again but this time at the instruction mockStatic(StaticClass.class) which throw the exception org.powermock.api.mockito.ClassNotPreparedException. Why the @PrepareForTest is executed only at the first run but not when the test is re-run.

1

There are 1 best solutions below

0
On

I think the problem was caused by PowerMock when he creat a deep clone of my rules. To overcome this problem I used JUnit rule chain :

RuleChain.outerRule((base, description) -> {
        try {
            final FrameworkMethod method = new FrameworkMethod(
                    description.getTestClass().getMethod(description.getMethodName()));
            return (new PowerMockRule()).apply(base, method, this);
        } catch (NoSuchMethodException | SecurityException e) {
            throw new RuntimeException(e);
        }
    }).around(myRetryRule).around(otherRules).....

A more generale soulution for this problem is proposed here MergedRule, 2, 3.