有一个黑盒类,它Thread
使用它的构造函数创建一个接受一个实例Runnable
作为参数的:
public class Service {
public static Task implements Runnable {
@Override
public void run() {
doSomeHeavyProcessing();
}
}
public void doAsynchronously() {
new Thread(new Task()).start();
}
}
我想拦截构造函数调用并获取对传递Task
implementation的引用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
对象的引用?我想在当前(主)线程中执行异步代码,或者加入创建的线程并执行断言。