2012-11-14 73 views
7

我想让RunWith(PowerMockRunner.class)使用我现有的包注释。RunWith(PowerMockRunner.class)不能使用包注释

版本:

powermock 1.4.12 1.9.0的Mockito的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); 
} 
} 

在UNITEST MockA.java,如果我不使用RunWith(PowerMockRunner.class),我会得到如预期的那样,thisVersion印刷0.1。但添加RunWith(PowerMockRunner.class)后,thisVersion变成null。我怀疑PowerMockRunner在包装注释这里做了一些有趣的事情,任何人有任何想法?看我下面的代码的迷你版:

+4

我考察的类加载器junit测试,当用'@RunWith(PowerMockRunner.class)'注释时。看来Powermock正在设置它自己的类加载器,这就是将模拟类注入测试用例的魔力。我很害怕你是对的,powermock生成的类的包不再被注释。 – Alban

+0

@Alban很好的发现!任何工作? – Shengjie

+2

我很害怕没有。深入研究你的问题,我检查了A.class',发现你在package上设置的注释实际上被替换为代理。所以'getAnnotation(TestAnnotation.class)'返回null。如果您遍历了包上的注释列表,则没有注释是TestAnnotation.class的实例或超类实例。实际上在包上的注释是代理。我没有找到一种方法来指示MockClassLoader将系统类加载器加载到A以外的任何类。根据java文档,这是可能的。 – Alban

回答

4

@阿尔班在评论侦探建立在,它看起来像添加此批注测试用例应该绕过这个问题:

@PowerMockIgnore("com.smin.dummy.TestAnnotation") 
相关问题