question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mocking static methods not working anymore since version 4.2.0

See original GitHub issue

Hello, recently I tried to upgrade to the latest Mockito version from 4.1.0 to 4.2.0 which resulted in a failing build. I noticed that the unit tests which used mockstatic was not passing anymore. I can share a simple code snippet which worked and does not work anymore with the latest version:

FooUtils

public final class FooUtils {

    private FooUtils() {}

    public static String getName() {
        return "Foo";
    }

}

Unit Test

import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;

import static org.assertj.core.api.Assertions.assertThat;

class FooTest {

    @Test
    void getName() {
        try (MockedStatic<FooUtils> mockedFooUtils = Mockito.mockStatic(FooUtils.class, InvocationOnMock::getMock)) {
            mockedFooUtils.when(FooUtils::getName).thenReturn("bar");
            String name = FooUtils.getName();
            assertThat(name).isEqualTo("bar");
        }
    }

}

The test fails and I am getting the following error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Default answer returned a result with the wrong type:
Class cannot be returned by getName()
getName() should return String

The default answer of FooUtils.class that was configured on the mock is probably incorrectly implemented.

See also this project where I use mockstatic: https://github.com/Hakky54/sslcontext-kickstart The master branch is with mockito 4.1.0 which passes however this pull request where the latest version is being used fails: https://github.com/Hakky54/sslcontext-kickstart/pull/135

I am using Java 8, 11 and 17 and it fails on all of them. I am using mockito-junit-jupiter. Any idea what could be the cause? Do you think I am using the mockstatic wrong or do I need additional configuration for the latest version?

Looking forward to hear from you guys soon.

Hakan,

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:9 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
temp-droidcommented, Jan 2, 2022

Hey @Hakky54 ,

Do you think I have incorrectly used mocking with mockstatic or do you think there is a bug in the latest version? I never had this issue with the initial test until the latest version.

It looks to me your implementation was wrong (because you don’t return a List), and your attempt to fix it (casting the invocation.getMock() to a List) avoids the type verification that would throw an error.

And because you mock it again after (certificateUtilsMockedStatic.when(() -> CertificateUtils.getRootCaFromAuthorityInfoAccessExtensionIfPresent(any(X509Certificate.class))) .thenReturn(Collections.emptyList());), it overrides your previous configuration and makes the test pass. If you remove the certificateUtilsMockedStatic.when( part, your test should still pass. But in that case your first mock should return a valid List, otherwise you will face java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.util.List.

In the end, you could use:

        try (MockedStatic<CertificateUtils> certificateUtilsMockedStatic = mockStatic(CertificateUtils.class, invocation -> {
            Method method = invocation.getMethod();
            if ("getRootCaFromAuthorityInfoAccessExtensionIfPresent".equals(method.getName())) {
                return Collections.emptyList();
            } else {
                return invocation.callRealMethod();
            }
        })) {

            X509Certificate certificate = (X509Certificate) certificates.get(certificates.size() - 1);
0reactions
Hakky54commented, Jan 2, 2022

Thank you for taking your time to look at this issue, and yes I totally agree with you that my test setup was not correct and adjusting it from my side fixes all the failing tests. I think we can close this issue as it is not an issue

Read more comments on GitHub >

github_iconTop Results From Across the Web

Why doesn't Mockito mock static methods? - Stack Overflow
I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib).
Read more >
MockedStatic (Mockito 4.2.0 API) - javadoc.io
Represents an active mock of a type's static methods. The mocking only affects the thread on which this static mock was created and...
Read more >
How to use the Mockito's inline mock maker - David Vlijmincx
Write better tests by mocking the constructor, static methods, have stricter mocking, mock final classes/methods, and easy-to-use argument ...
Read more >
Mocking Static Methods With Mockito - Baeldung
In this tutorial, we'll take a look at how we can now mock static methods using the latest version of Mockito. To learn...
Read more >
Enable mocking static methods in Mockito #1013 - GitHub
Research + discuss whether it is a good idea to enable static methods mocking in Mockito. The theory is that it is useful...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found