javaunit-testingtestingmockitotry-catch

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?

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.