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

dig*_*tig 7 java mockito

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

abstractForm.isPresent() && (abstractForm.get().getClass() != this.getClass())
Run Code Online (Sandbox Code Playgroud)

(不是我的设计 - 不要怪我!)并且需要为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
Run Code Online (Sandbox Code Playgroud)

所以它现在有效,但不太可能继续工作。这是否超出了 Mockito 可以做的范围,或者是否有一种非弃用的方式来获得 Mockito 模拟对象的类?

avi*_*rat 9

在我寻找答案时偶然发现了这个问题。我从这个 github 问题中意识到我使用的是旧版本的 mockito。

我只是从这个版本更新

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

到这个版本

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.2.4</version>
            <scope>test</scope>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

诀窍是artifactId已经改变了,谷歌会artifactId在查找“mockito maven”时向您发送指向旧版本的链接。