23

I am trying to mock a final class

PowerMockito.mockStatic(TestFinalClass.class);

It is working from my eclipse when I run a single junit and add javaagent to my VM arguments

-javaagent:{path}/powermock-module-javaagent-1.6.4.jar

But when I try to run all test cases from command line using maven build command I am still getting "Cannot subclass final class"

Below is my snippet from pom.xml

            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <argLine>-javaagent:{path}/powermock-module-javaagent-1.6.4.jar</argLine>
            </configuration>
        </plugin>
user3755282
  • 813
  • 2
  • 9
  • 15

3 Answers3

37
package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(FinalClass.class)
public class Tests {
    @Test
    public void test() {
    PowerMockito.mockStatic(FinalClass.class);
    }
}

This works for me. If you add 'PowerMockRunner' and 'PrepareForTest' annotations you don`t need to use extra vm arguments.

wprzechodzen
  • 619
  • 4
  • 13
3
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(FinalClass.class)
public class TestFinalClass{

    @Test
    public void whenMockFinalClassMockWorks() {

        FinalClass finalklass = PowerMockito.mock(FinalClass.class);
    }
}
Halim
  • 66
  • 3
0

I got the code coverage using JaCoCo and need to make some changes related to it in the test class code. Those are as below:

  1. I removed @RunWith annotation

  2. Added @Rule and PowerMockRule class

  3. Mentioned the Final and Static class in @PrepareForTest

    @PrepareForTest(FinalClass.class, StaticClass.class)

    public class Tests {

    @Rule
    public PowerMockRule rule = new PowerMockRule();
    
    @Test
    public void test() {
        PowerMockito.mockStatic(FinalClass.class);
        PowerMockito.mockStatic(StaticClass.class);
    }
    

    }

Also added the argline in surefire to overcome the final class problem while mocking.

<configuration>
                <argLine>-javaagent:{path}/powermock-module-javaagent-1.6.4.jar</argLine>
            </configuration>
Atul
  • 3,043
  • 27
  • 39