I've investigated how to raise a Thread.sleep interrupt exception in JUnit, so I'll leave it as a reminder.
■ Environment Java 8 JUnit 4
Wake up "interrupt thread" from "test running thread". Interrupts from the "interrupt thread" to the "test running thread".
In order to interrupt, it is necessary to tell "thread running test" to "thread for interrupt"
You can get the thread that is executing processing with Thread.currentThread ()
.
Code to be tested
public class SampleClass {
public void sample() throws InterruptedException {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw e;
}
}
}
Test code
@Test
public void testSample() {
try {
//Define a thread for interrupts
final class InterruptThread extends Thread {
Thread targetThread = null;
public InterruptThread(Thread thread) {
targetThread = thread;
}
@Override
public void run() {
try {
Thread.sleep(100);
targetThread.interrupt();
} catch (InterruptedException e) {
}
}
}
//Start an interrupt thread
InterruptThread th = new InterruptThread(Thread.currentThread());
th.start();
//Run the code under test
SampleClass target = new SampleClass();
target.sample();
fail();
} catch (InterruptedException e) {
assertEquals(e.getMessage(), "sleep interrupted");
}
}
Recommended Posts