Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powermock mockstatic Cannot subclass final class

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>
like image 967
user3755282 Avatar asked Aug 26 '16 17:08

user3755282


2 Answers

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.

like image 81
wprzechodzen Avatar answered Oct 29 '22 13:10

wprzechodzen


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);
    }
}
like image 3
Halim Avatar answered Oct 29 '22 13:10

Halim