のインスタンスを引数としてThread
受け入れるコンストラクターを使用してを作成するブラック ボックス クラスがあります。Runnable
public class Service {
public static Task implements Runnable {
@Override
public void run() {
doSomeHeavyProcessing();
}
}
public void doAsynchronously() {
new Thread(new Task()).start();
}
}
Task
コンストラクター呼び出しをインターセプトし、渡された実装への参照を取得したいと考えていますRunnable
。これまでのコードは次のとおりです。
@RunWith(PowerMockRunner.class)
@PrepareForTest(Service.class)
public class ServiceTest {
@Test
public void testService() {
ArgumentCaptor<Runnable> runnables = ArgumentCaptor.forClass(Runnable.class);
Thread thread = Mockito.mock(Trhead.class);
whenNew(Thread.class.getContructor(Runnable.class)).
withArguments(runnables.capture)).thenReturn(thread);
new Service().doAsynchronously();
System.out.println("all runnables: " + runnables.getAllValues());
for (Runnable r : runnables.getAllValues()) r.run();
// perform some assertions after the code meant to be executed in a new
// thread has been executed in the current (main) thread
}
}
テストを実行すると、次のように出力されます。
all runnables: []
コンストラクターによって返されたすべてのRunnable
オブジェクトまたはオブジェクトへの参照を取得する方法はありますか? Thread
現在の (メイン) スレッドで非同期コードを実行するか、作成されたスレッドに参加してアサーションを実行したいと考えています。