2015-02-10 75 views
0

我有以下类:如何测试异步线程方法被调用?

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写吗?

回答

0

夫妇的事情要考虑:

  1. 由于您使用的外螺纹,一些kindof等待/阻塞是必要
  2. 如果线程代码更加复杂,并且由于我们需要等待线程完成一般来说的执行(而不是您的情况),则需要使用超时功能。
  3. 您不必一定要使用模拟,例如, FooClass.bar()方法可以设置/修改一个字段,然后检查一个更改的值。

    @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(); 
    } 
    
+0

我认为我不应该使用超时。 – gstackoverflow 2015-02-10 14:11:07

+0

嗯,这取决于。在你的情况下,因为它是一个微不足道的代码,所以你不必使用'timeout'参数,因为线程执行速度非常快。 – Crazyjavahacking 2015-02-10 14:17:46

+0

但通常如果线程执行可能更长更复杂,应始终使用@Test(timeout ...)。 – Crazyjavahacking 2015-02-10 14:18:17