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.

Mocked static methods are not available in other threads

See original GitHub issue
  • The mockito message in the stacktrace have useful information, but it didn’t help
  • The problematic code (if that’s possible) is copied here; Note that some configuration are impossible to mock via Mockito
  • Provide versions (mockito / jdk / os / any other relevant information)
  • Provide a Short, Self Contained, Correct (Compilable), Example of the issue (same as any question on stackoverflow.com)
  • Read the contributing guide

Mockito v3.4.0

Mockito.mockStatic() mocks method seems to be working in the current thread only. I need the static mock to be available globally in multiple threads.

for e.g:

try ( MockedStatic<LegacyTextUtils> utilMock = Mockito.mockStatic(LegacyTextUtils.class)){
    utilMock.when(LegacyTextUtils::getReqText).thenReturn("test-123");
}

The above mock is only available in the current thread. Is there any way to make it available globally?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:45
  • Comments:9

github_iconTop GitHub Comments

4reactions
cytoe1commented, May 10, 2021

Same problem here. As workaround you can mock ExecutorServices, but probably it will not work with all code. Need to be analysed case by case.

This workaround worked for me. Thanks @bastiao !

Executor executor = you executor....;
doAnswer(new Answer<Object>() {
    public Object answer(InvocationOnMock invocation)
        throws Exception {
        Object[] args = invocation.getArguments();
        Runnable runnable = (Runnable)args[0];
        try (MockedConstruction<SomeClass> mockedConstructor = Mockito.mockConstruction(SomeClass.class);
              MockedStatic<SomeStaticUtil> mockedUtil = mockStatic(SomeStaticUtil.class))
        {
            ....do mocks things
            runnable.run();
        }
        return null;
    }
}).when(executor).execute(any());
2reactions
ngocnam1202commented, Sep 23, 2021

@Ignore on the methods have mockStatic (1) Write a method to call (1) async Ex:


    @Test
    public void testForMockStaticUsing() {
        log.info("Async to Avoid MockitoException [static mocking is already registered in the current thread]");
        CompletableFuture.runAsync(() -> testEncrypt_null_or_exception());
        CompletableFuture.runAsync(() -> testDecrypt_null_or_exception());
    }

    @Ignore
    void testEncrypt_null_or_exception() {
        log.info("Mocking");
        Mockito.mockStatic(JWT.class);
        Mockito.when(JWT.create()).thenThrow(new RuntimeException());
        ...
    }

    @Ignore
    void testDecrypt_null_or_exception() {
        log.info("Mocking");
        Verification verification = Mockito.mock(Verification.class);
        Mockito.mockStatic(JWT.class);
        Mockito.when(JWT.require(any(Algorithm.class))).thenReturn(verification);
        ...
    }

Read more comments on GitHub >

github_iconTop Results From Across the Web

mockito mock static function does not work if the function is ...
There seem to be a few things wrong with your test: Don't mock static methods. Refactor your code to use an interface and...
Read more >
Static method call not being mocked on some threads using ...
This mocking of Realm.getDefaultInstance() works completely fine with simple RxJava observable chains/trees even when some of them are executed in different ...
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.
Read more >
Mocking static methods made possible in Mockito 3.4.0
The mocked static method is only visible in the try-with-resources block. Different outcomes can be tested in isolation. · Static methods can ...
Read more >
MockedStatic (Mockito 3.4.3 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 >

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