Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reflection with Mockito mock objects

Tags:

java

mockito

I'm trying to test some Java code that uses reflection, and as part of the test I need to create an object that is a different type to the object under test but that shares the same (abstract) parent (actually, an Optional wrapping the object). I am testing a predicate of the form:

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

(not my design - don't blame me!) and need to create a mock object for abstractForm. If I create it with Mockito, simply using SacmElement citedElement = mock(SacmElement.class) it actually all works just fine except I get a warning:

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

So it works for now, but it isn't likely to keep working. Is this going beyond what Mockito can do, or is there a non-deprecated way of getting at the class of a Mockito mocked object?

like image 404
digitig Avatar asked Jul 03 '18 18:07

digitig


1 Answers

Just stumbled into this question while I was searching for its answer. I realized from this github issue that I was using an old version of mockito.

I simply updated from this version

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

to this version

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

The trick was that the artifactId has changed and that Google sends you the link to the older artifactId on lookup for "mockito maven".

like image 197
avi.elkharrat Avatar answered Nov 04 '22 12:11

avi.elkharrat