Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I test the 'catch' portion of code in a try-catch, using Mockito, when the 'try' is 'Thread.Sleep()?

I’m using mockito to write test, but I’m really struggling with how to test this specific bit of code:

public void myMethod() {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

A lot of examples online use the example of forcing whatever is in the try to throw an error – but everything I’ve looked at yells ‘don’t mock a Thread’

Is there a way I can force the code to be interrupted using Thread.interrupt() or similar?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I did start to try and use a spy:

Thread threadSpy = spy(new Thread());
threadSpy.interrupt();
assertThatExceptionOfType(RuntimeException.class);

but I can see that this isn’t actually causing the thread in myMethod to interrupt, so isn’t actually testing that bit of code.

>Solution :

Here is the test

public class AppTest {
    @SneakyThrows
    @Test
    void test() {
        AtomicReference<Throwable> reference = new AtomicReference<>();
        Thread thread = new Thread(() -> {
            try {
                myMethod();
            } catch (Throwable t) {
                reference.set(t);
            }
        });

        thread.start();
        thread.interrupt();
        thread.join();
        assertNotNull(reference.get());
    }

    public void myMethod() {
        try {
            Thread.sleep(400);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Make sure that sleep value is sufficiently large.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading