'Using mockito any() throws java.lang.IllegalAccessError: class org.mockito.Matchers tried to access private method

I'm facing the exception

java.lang.IllegalAccessError: class org.mockito.Matchers tried to access private method 'void org.mockito.internal.progress.ThreadSafeMockingProgress.()' (org.mockito.Matchers and org.mockito.internal.progress.ThreadSafeMockingProgress are in unnamed module of loader 'app')

at org.mockito.Matchers.(Matchers.java:107)

when I try to use the matcher any() in mockito when() stub call. The class argument type is for "NewOrder" from the binance spot java library here

I'm trying to do

when(mockBinanceApiRestClient.newOrder(any(NewOrder.class))).thenReturn(buyOrderResp);

mocking the BinanceApiRestClient. The any() and when() are static imports from org.mockito.Mockito. This is such a nightmare why it wouldn't work. Any help is much appreciated.



Solution 1:[1]

Looks like you have two conflicting versions of Mockito on your classpath.

ThreadSafeMockingProgress was converted to a singleton back in 2016, and its constructor was changed to private.

On the other hand, you seem to be using org.mockito.Matchers, which was deprecated for a long while and finally removed in Mockito 4.x

Solution 2:[2]

I also faced similar issue when we used below dependency -

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

we had below import statements which were causing IllegalAccess exception

import static org.mockito.Matchers.any;

I replaced Matchers with ArgumentMatchers as below -

import static org.mockito.ArgumentMatchers.any;

This resolved the issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lesiak
Solution 2 Priyanka Pingale