如何在Mockito模拟对象中使用反射

时间:2018-07-03 18:04:09

标签: java mockito

我正在尝试测试一些使用反射的Java代码,并且作为测试的一部分,我需要创建一个与被测试对象类型不同但共享相同(抽象)父对象的对象(实际上, Optional包装对象)。我正在测试以下形式的谓词:

abstractForm.isPresent() && (abstractForm.get().getClass() != this.getClass())

(不是我的设计-不要怪我!),需要为abstractForm创建一个模拟对象。如果我使用Mockito创建它,只需使用SacmElement citedElement = mock(SacmElement.class)实际上所有功能都可以正常运行除了我会收到警告:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.mockito.cglib.core.ReflectUtils$2 (file:/C:/Users/owner/.m2/repository/org/mockito/mockito-core/1.10.19/mockito-core-1.10.19.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.mockito.cglib.core.ReflectUtils$2
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

因此它暂时可以使用 ,但是不太可能继续工作。这是否超出了Mockito的能力范围,还是有不折不扣的获取Mockito模拟对象类的方法?

1 个答案:

答案 0 :(得分:5)

当我在寻找答案时,偶然发现了这个问题。我从this github issue意识到我正在使用旧版本的Mockito。

我只是从此版本更新

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>

此版本

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.2.4</version>
            <scope>test</scope>
        </dependency>

诀窍是artifactId已更改,并且Google在查找“ mockito maven”时向您发送了指向较旧的artifactId的链接。

相关问题