我试图在现有的包注释中使用RunWith(PowerMockRunner.class)。
版本:
powermock 1.4.12,mockito 1.9.0,junit 4.8.2
package-info.java // 这是用于包注释的文件
@TestAnnotation(version="1.0")
package com.smin.dummy;
TestAnnotation.java // 这是用于“com.smin.dummy”包的元数据注释类
package com.smin.dummy;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface TestAnnotation {
String version();
}
A.java
package com.smin.dummy;
public class A {
private static Package myPackage;
private static TestAnnotation version;
static {
myPackage = TestAnnotation.class.getPackage();
version = myPackage.getAnnotation(TestAnnotation.class);
}
public static String getVersion() {
return version.version();
}
}
MockA.java
package com.smin.dummy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.smin.dummy.A;
@RunWith(PowerMockRunner.class) //comment out this line to see the difference
@PrepareForTest(A.class)
public class MockA {
@Test
public void test_mocked() throws Throwable {
String thisVersion = A.getVersion();
System.out.println(thisVersion);
}
}
在单元测试中的 MockA.java 中,如果我不使用
RunWith(PowerMockRunner.class)
,我会像预期的那样打印出 thisVersion
的值为 0.1
。但是在添加了 RunWith(PowerMockRunner.class)
后,thisVersion
的值变成了 null
。我怀疑 PowerMockRunner 在这里对包注释做了一些有趣的事情,请问有人有什么想法吗?以下是我代码的迷你版本:
@RunWith(PowerMockRunner.class)
注解时,我检查了junit测试的类加载器。看起来Powermock正在设置自己的类加载器,这就是将模拟类注入到测试用例中的神奇方式。恐怕你说得对,由Powermock生成的类的包不再如预期那样被注释。 - AlbangetAnnotation(TestAnnotation.class)
返回 null。如果您遍历包上的注释列表,就不会有任何一个注释是 TestAnnotation.class 的实例或超类实例。事实上存在于包上的注释是一个代理。我找不到一种方法来指示 MockClassLoader 延迟加载除 A 以外的任何类的系统类装载器。根据 Java 文档,这是可能的。 - Alban