Java Powermock mockstatic 不能子类化 final 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39171894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Powermock mockstatic Cannot subclass final class
提问by user3755282
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
当我运行单个 junit 并将 javaagent 添加到我的 VM 参数时,它在我的 Eclipse 中工作
-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"
但是当我尝试使用 maven build 命令从命令行运行所有测试用例时,我仍然收到“无法子类化最终类”
Below is my snippet from pom.xml
下面是我的 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>
回答by wprzechodzen
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.
这对我有用。如果添加 'PowerMockRunner' 和 'PrepareForTest' 注释,则不需要使用额外的 vm 参数。
回答by Halim
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);
}
}