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.
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.And in your test
I definitely prefer the shorter version. :)