我目前正在编写一些涉及JMock的测试。我无法理解代码的以下结构:

context.checking(new Expectations() {  //context is of type Mockery of course
            {
                allowing(csv).getFileName();
                will(returnValue(fileName));
            }
        });

据我所知,分析缓慢
context.checking(new Expectations() { ... }

这将生成Expectations的实例化。但是,为什么在此之后又要加上另一个括号,然后我相信一些奇怪的静态方法,例如allowing()等?如果有人可以从Java的角度向我解释,这是怎么回事,我将不胜感激。

最佳答案

第二组花括号形成instance initialization block,编译器将其代码复制到该类的每个构造函数中。这使您可以访问实例成员。对于JMock的API,它提供了一种简洁的方法来初始化期望。您可以使用模板方法实现等效的功能(尽管在编译Expectations本身时会警告有关从构造函数对可重写方法的不安全调用)。

public abstract class Expectations {
    public Expectations() {
        buildExpectations();
    }

    protected abstract void buildExpectations();

    ...
}

并在您的测试中
context.checking(new Expectations() {
    protected void buildExpectations() {
        allowing(csv).getFileName();
        will(returnValue(fileName));
    }
});

我绝对更喜欢较短的版本。 :)

09-04 06:45