Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JMock - strange syntax for adding expectations

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.

like image 317
Bober02 Avatar asked May 26 '12 19:05

Bober02


People also ask

How do you write expectations in Mockito?

new Expectations() {{ ... // An expectation for an instance method: mockInstance. someMethod(1, "test"); result = "mocked"; ... }}; // A call to code under test occurs here, leading to mock invocations // that may or may not match specified expectations. }

What is JMock in Java?

JMock is a library that supports test-driven development of Java code with mock objects . Mock objects help you design and test the interactions between the objects in your programs. The jMock library: makes it quick and easy to define mock objects, so you don't break the rhythm of programming.


1 Answers

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. :)

like image 85
David Harkness Avatar answered Sep 23 '22 00:09

David Harkness