与mockito在线程上的间谍私人方法

时间:2013-08-26 13:55:53

标签: java multithreading mockito powermock

我有一个runnable,在他的一生中调用一个void私有方法。 我想使用PowerMockito测试我的方法“processStep”实际上只为每个参数调用一次。

MyRunnable class

public class MyRunnable extends Runnable {
    MyRunnable(args){
    ...
    }

@Override
public final void run{
    ...
        processStep();
        ...
    }

private void processTep(a){
        ...
        addAttributeResult();
        ...
    }

private void addAttributeResult(){
    ...
    }
}    

我的测试MyRunnable类的测试类

@PowerMockIgnore("org.apache.log4j.*")
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DBReader.class, MyRunnable.class })
public class CycleManagerTest {
    @Test
    public void myTest(){
        MyRunnable myRunnable = new MyRunnable(arg[] {a,b});
        Thread t = new Thread(myRunnable);
        t.start();
        while (myRunnable.getNbrEndCycle() < 1) {
            Thread.sleep(10);
        }
        t.interrupt();
                    for(String s : arg){
                        PowerMockito.verifyPrivate(myRunnable, times(1)).invoke("processStep", a);
                    }
    }
}

当只有一个参数时,测试成功但是当有很多参数时,测试出现错误,如下所示:

*org.mockito.exceptions.misusing.UnfinishedVerificationException: 
Missing method call for verify(mock) here:
-> at fr.MyRunnable.addAttributeResult(MyRunnable.java:254)
Example of correct verification:
    verify(mock).doSomething()
Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.*

我真的不明白发生了什么。我觉得我在某个地方完全错了。

1 个答案:

答案 0 :(得分:2)

@PrepareForTest注释应引用包含要测试的私有方法的类,此处为MyRunnable。请参阅https://code.google.com/p/powermock/wiki/MockitoUsage13的最后一个示例。