JMock - strange syntax for adding expectations
Asked Answered
W

3

7

I am currently writing a couple of tests involving JMock. I cannot understand the following structure of the code:

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

Analysing slowly, as far as I know,

context.checking(new Expectations() { ... }

This will generate an anonoymous instantiateion of Expectations. But why do we have another brackets right after this, and then some strange, static I believe, methods such as allowing() etc? If someone could explain to me from Java point of view what is going on here I would be very grateful.

Weighin answered 26/5, 2012 at 19:13 Comment(0)
C
6

The second set of braces form an instance initialization block, and its code is copied by the compiler into every constructor for the class. This gives you access to the instance members. In the case of JMock's API, it provides a terse way to initialize the expectations. You could achieve the equivalent thing (though with a warning when compiling Expectations itself about an unsafe call to an overridable method from the constructor) with a template method.

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

    protected abstract void buildExpectations();

    ...
}

And in your test

context.checking(new Expectations() {
    protected void buildExpectations() {
        allowing(csv).getFileName();
        will(returnValue(fileName));
    }
});

I definitely prefer the shorter version. :)

Chirp answered 26/5, 2012 at 20:12 Comment(0)
J
6

Instance initializers are interesting. They only place I have really seen them used a lot is with JMock. Consider a simpler more understandable context. You can create a map and add items to it:

Map<String,String> map = new HashMap<String,String>(){
    {
        put("One","Something");
        put("Two","Other");
    }
};

Maybe this will help you to see what JMock is doing.

Jenness answered 26/5, 2012 at 20:12 Comment(0)
C
1

Some people believe that creating expectations in static initialisers, with static methods provides cool looking , terse, fluent and easily readable syntax for specifying expectations - and I agree with them. Awkward syntax is not only cool thing in mocking frameworks - there is lot of cool bytecode manipulation under the hood.

Cowley answered 26/5, 2012 at 19:50 Comment(1)
Not really answering my question I'm afraidWeighin

© 2022 - 2024 — McMap. All rights reserved.