如何测试调用了异步线程方法?

How to test that in async thread method was invoked?

我关注类:

public class ForTest {
    public void methodToTest(Thread thread){
        thread.start();
    }
}
class MyThread extends Thread{
    FooClass fooClass;
    public MyThread(FooClass fooClass){
        this.fooClass = fooClass;
    }
    @Override
    public void run() {
        fooClass.bar();
    }
}
class FooClass{
    public void bar(){}
}

我想测试方法methodToTest
我想将 MyThread 的实例作为上述方法的参数传递。

因此,我想验证是否调用了方法 bar

你能帮我用 Mockito 或 Powermock 写吗?

需要考虑的几件事:

  1. 因为你使用的是外螺纹,需要某种waiting/blocking
  2. 如果线程代码比较复杂,一般来说我们需要等待线程执行完毕(不是你的情况),就需要使用超时功能。
  3. 您根本不必使用模拟,例如FooClass.bar() 方法可以 set/modify 一个字段,然后检查该字段是否有更改的值。

    @Test
    public void testSomeMethod() throws InterruptedException {
        FooClass fooClassMock = Mockito.mock(FooClass.class);
        Thread thread = new MyThread(fooClassMock);
    
        new ForTest().methodToTest(thread);
    
        thread.join();
    
        Mockito.verify(fooClassMock).bar();
    }