有一个黑盒类,它使用接受Runnable实例作为参数的构造函数来创建Thread:
public class Service {
public static Task implements Runnable {
@Override
public void run() {
doSomeHeavyProcessing();
}
}
public void doAsynchronously() {
new Thread(new Task()).start();
}
}我想截取构造函数调用,并获取对实现Runnable的传递Task的引用。这是目前为止的代码:
@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对象的引用?我希望在当前(主)线程中执行异步代码,或者连接创建的线程并执行断言。
发布于 2011-10-13 23:19:47
首先,您的代码有一些拼写错误,一旦更正,在IDE中尝试时就不能正常工作。代码抛出一个关于Task初始化的VerifyError。制作Task public很有帮助。
一旦一切正常,你的代码就会按预期工作,这意味着你的可运行代码被捕获了。
尽管我会使用这种存根语法:
whenNew(Thread.class).withParameterTypes(Runnable.class)
.withArguments(runnables.capture()).thenReturn(mock);你应该调查你的真实代码,看看它是否被正确地存根了。
https://stackoverflow.com/questions/7752476
复制相似问题