How to mock and throw an InterruptedException when Thread.sleep() is called.
@Component
public class SomeClass
public String myMethod() {
// do Something
try {
Thread.sleep(3000);
} catch (final InterruptedException ignored) {
log.warn("Interrupted!", ignored);
}
return "Hello";
}
}
I would want to throw an InterruptedException when Thread.sleep() is called. How can I do that with JUnit5 and Mockito
CodePudding user response:
Don't attempt to use mockStatic
in this case.(I failed)
For testability, you should extract a sleep
method in this case(maybe even a class for sleep), it is quite similar to mocking system time with Clock
.
@Component
public class SomeClass {
public String myMethod() {
// do Something
try {
sleep();
} catch (final InterruptedException ignored) {
log.warn("Interrupted!", ignored);
}
return "Hello";
}
void sleep() throws InterruptedException {
Thread.sleep(3000);
}
}
Then you can simply test it like
class SomeClassTest {
@Test
public void Should_logWarning_When_sleepInterrupted() throws InterruptedException {
SomeClass someClass = spy(new SomeClass());
doThrow(InterruptedException.class).when(someClass).sleep();
// Do assertion...
}
}
CodePudding user response:
If you would like to get an InterruptedException
in your code you have to simply interrupt the thread, there's no need to mock anything. An example of a simple call with interruption would be:
@Test
void interrupt() {
var object = new SomeClass();
// runnable passed to the thread contructor
var thread = new Thread(object::myMethod);
thread.start();
thread.interrupt();
}
This results in execution of the catch
body (printing the "Interrupted!" message).