LoginSignup
3
2

More than 5 years have passed since last update.

Thread.sleep中の割り込みをJUnitでテストする方法

Posted at

はじめに

Thread.sleepの割り込み例外発生をJUnitで起こす方法を調べたので、備忘として残します。

■環境
Java 8
JUnit 4

概要

「テスト実行中スレッド」から「割り込み用スレッド」を起こします。
「割り込み用スレッド」から「テスト実行中スレッド」へ割り込みをかけます。

割り込みをかけるために、「割り込み用スレッド」には「テスト実行中スレッド」を教えておく必要があります
Thread.currentThread()で処理実行中のスレッドを取得することができます。

コード

テスト対象コード
public class SampleClass {
    public void sample() throws InterruptedException {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw e;
        }
    }
}
テストコード
@Test
public void testSample() {
    try {
        // 割り込み用スレッドを定義する
        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) {
                }
            }
        }

        // 割り込み用スレッドを開始する
        InterruptThread th = new InterruptThread(Thread.currentThread());
        th.start();

        // テスト対象コードを実行する
        SampleClass target = new SampleClass();
        target.sample();
        fail();
    } catch (InterruptedException e) {
        assertEquals(e.getMessage(), "sleep interrupted");
    }
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2