我需要模拟一个类的静态方法,并在我的测试中使用该模拟方法。现在看来我只能使用PowerMock来做到这一点。
我使用@RunWith(PowerMockRunner.class)和@PrepareForTest使用适当的类注释该类。
在我的测试中,我有一个@ClassRule,但在运行测试时,规则未正确应用。
我该怎么办?
RunWith(PowerMockRunner.class)
@PowerMockIgnore({
"javax.xml.*",
"org.xml.*",
"org.w3c.*",
"javax.management.*"
})
@PrepareForTest(Request.class)
public class RoleTest {
@ClassRule
public static HibernateSessionRule sessionRule = new HibernateSessionRule(); // this Rule doesnt applied
答案 0 :(得分:2)
我查看了PowerMock代码。看起来PowerMockRunner
不支持@ClassRule
。您可以尝试将HibernateSessionRule
用作@Rule
而不是@ClassRule
。
@PrepareForTest(Request.class)
public class RoleTest {
@Rule
public HibernateSessionRule sessionRule = new HibernateSessionRule();
答案 1 :(得分:2)
解决此问题的另一种方法是使用org.powermock.modules.junit4.PowerMockRunnerDelegate
批注:
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class)
@PowerMockIgnore({
"javax.xml.*",
"org.xml.*",
"org.w3c.*",
"javax.management.*"
})
@PrepareForTest(Request.class)
public class RoleTest {
@ClassRule
public static HibernateSessionRule sessionRule = new HibernateSessionRule(); // this Rule now applied
答案 2 :(得分:-1)
我发现另一种解决方案仅对PowerMock 1.4或主要版本有效。我将这些依赖项添加到了pom.xml
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-classloading-xstream</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
并更改了代码,删除了@RunWith
批注并使用了一个简单的JUnit @Rule
@PrepareForTest(X.class);
public class MyTest {
@Rule
PowerMockRule rule = new PowerMockRule();
// Tests goes here
...
}
有关更多信息,请访问PowerMock的documentation