JMock - weird syntax for adding expectations

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

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

Analyzing slowly, as far as I know,

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

This will create an anonymous instance of Expectations . But why do we have other brackets right after that, and then some weird, static methods, I think, such as allow (), etc.? If someone could explain to me from the point of view of Java what is happening here, I would be very grateful.

+7
source share
3 answers

The second set of curly braces is an instance initialization block, and its code is copied by the compiler into each constructor for the class. This gives you access to instance members. In the case of the JMock API, it provides a short way to initialize expectations. You could achieve the equivalent thing (albeit with a warning when compiling Expectations about an unsafe invocation of an overridable method from the constructor) using the 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. :)

+6
source

Instance initializers are interesting. They only bet that I really saw that they are used a lot with JMock. Consider a more understandable and understandable context. You can create a map and add elements to it:

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

Perhaps this will help you see what JMock is doing.

+6
source

Some people think that creating expectations in static initializers with static methods provides a cool, lightweight, lightweight, and easy to read syntax for defining expectations - and I agree with them. The awkward syntax is not only a cool thing in mocking frameworks - there are a lot of cool bytecodes around the hood.

+1
source

All Articles