首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用PowerMock(ito)获取对传递给线程构造函数的可运行实例的引用?

如何使用PowerMock(ito)获取对传递给线程构造函数的可运行实例的引用?
EN

Stack Overflow用户
提问于 2011-10-13 18:04:39
回答 1查看 2K关注 0票数 0

有一个黑盒类,它使用接受Runnable实例作为参数的构造函数来创建Thread

代码语言:javascript
复制
public class Service {

  public static Task implements Runnable {

    @Override
    public void run() {

      doSomeHeavyProcessing();
    }
  }

  public void doAsynchronously() {

    new Thread(new Task()).start();
  }
}

我想截取构造函数调用,并获取对实现Runnable的传递Task的引用。这是目前为止的代码:

代码语言:javascript
复制
@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
  }
}

测试执行将打印出来:

代码语言:javascript
复制
all runnables: []

有没有一种方法可以获取构造函数返回的所有Runnable对象或Thread对象的引用?我希望在当前(主)线程中执行异步代码,或者连接创建的线程并执行断言。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-13 23:19:47

首先,您的代码有一些拼写错误,一旦更正,在IDE中尝试时就不能正常工作。代码抛出一个关于Task初始化的VerifyError。制作Task public很有帮助。

一旦一切正常,你的代码就会按预期工作,这意味着你的可运行代码被捕获了。

尽管我会使用这种存根语法:

代码语言:javascript
复制
whenNew(Thread.class).withParameterTypes(Runnable.class)
    .withArguments(runnables.capture()).thenReturn(mock);

你应该调查你的真实代码,看看它是否被正确地存根了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7752476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档