Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Not possible to mock Thread.sleep #3344

Open
5 tasks done
reftel opened this issue May 15, 2024 · 0 comments
Open
5 tasks done

Not possible to mock Thread.sleep #3344

reftel opened this issue May 15, 2024 · 0 comments

Comments

@reftel
Copy link

reftel commented May 15, 2024

When converting an existing testcase that uses PowerMock and EasyMock to use Mockito, I ran into a problem: the test used to use PowerMock.mockStatic(Thread.class) and then do

Thread.sleep(1000);
EasyMock.expectLastCall();

(etc.) to verify that the code paused for the intended time between retry attempts, without the test actually taking many seconds to run. With Mockito (version 5.12.0 on Java 17 for macOs), Mockito.mockStatic(Thread.class) fails, with the following error message (see below for SSCCE):

org.mockito.exceptions.base.MockitoException: It is not possible to mock static methods of java.lang.Thread to avoid interfering with class loading what leads to infinite loops

I can understand that some of the static methods on Thread cannot be safely mocked, but does that also apply to Thread.sleep? Is it possible to somehow do a partial static mock of Thread, so that sleep can be mocked?

  • 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

Short, self-contained compilable example:

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

public class SSCCE {
    public void productionCodeThatSleeps() throws InterruptedException {
        Thread.sleep(1000);
    }

    @Test
    public void testThreadSleep() throws Exception {
        try (MockedStatic<Thread> mockedStatic = Mockito.mockStatic(Thread.class)) {
            productionCodeThatSleeps();
            mockedStatic.verify(() -> Thread.sleep(1000));
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant