"Mockito cannot mock this class" error even if I am using powermockito to mock the class

240 views Asked by At

I have a final class

public final class A {
    private static final Set<String> B = methodA();

    private static Set<String> methodA() {
        //does some processing and 
        //returns a set 
    }

    public static boolean methodB() {
        //does some processing and 
        //returns a boolean 
    }
}

The class under test is class B. This class is calling the static method of the final class A

public class B {
    public boolean methodC() {
       if(methodB()) {
         C.methodD();
       }
    }
}

The class C is again a final class

public final class C {

    public static void methodD() {
        //does some processing
    }
}

I am mocking this final class A like this

public class TestB {

    public void testMethodC() {
        PowerMockito.mock(A.class); 
    }
}

The case is failing inside the methodD of class C.
I am getting this error Mockito cannot mock this class: A.

1

There are 1 answers

5
Renato On

You need some annotations:

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class})
public class TestB {

    public void testMethodC() {
        PowerMockito.mock(A.class); 
    }
}

My dependencies:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>