如果在模拟对象的方法中使用的对象只调用一次方法,如何在EasyMock中断言?

时间:2016-03-07 15:49:17

标签: easymock

我有一个使用EasyMock测试的课程:

public class Application {
    public void doSomething (AnotherObject o) {
        o.getA().perform();
    }   
}

Application的JUnit测试中,我需要断言perform()o.getA()返回的对象上被调用,并且只被调用一次。

传递给AnotherObject的{​​{1}}是否必须被嘲笑?

有没有办法使用EasyMock做到这一点?

1 个答案:

答案 0 :(得分:4)

您需要模拟A并记录该行为。 AnotherObject可能是模拟与否。您只需要getA返回A的模拟。

然后你会有类似的东西:

A a = createMock(A.class);
a.perform(); // this record one and only one call to perform()
replay(a);

AnotherObject another = new AnotherObject();
another.setA(a);

Application app = new Application()
app.doSomething(another);

verify(a); // this makes sure perform was call once instead of not at all