Coolest bit of Groovy

[sourcecode language=”groovy”]
void receiveMessage() {
TextWebSocketFrame result
def mockChannel = [write:{result=it;return null}] as Channel
def mockContext = [channel:{mockChannel}] as ChannelHandlerContext

def handler = new WebSocketServerHandler()
handler.messageReceived(mockContext, new TextWebSocketFrame("test"))

assert result.text == "test"

This has to be some of the most exciting code I’ve written all month (second to maybe a radial layout for an Android project). It is a snippet of Groovy which mocks two objects using maps and lambdas, and then, it tests a class I wrote, “WebSocketServerHandler”. Compared to a Java implementation of this unit test, the Groovy was very easy to write and understand.

Some of the things I really like”

  1. Optional semicolons I’m not a semicolon nazi, but in this case not having them makes the code much easier on the eyes.
  2. Duck Typing This is how the baked in mocking is allowed to work. “mockChannel” and “mockContext” provide method definitions and implementations. “as” causes a type cast for Java interoperability. When Java calls the code, Groovy looks for methods which look and sound like the method being called. Hence “duck” typing.
  3. Lambdas and Closures The definition of “mockChannel” is so much simpler than a Anonymous Inner class
  4. Implicit Return This made single line mocked methods much cleaner and more terse; though it did bite me at one point.
  5. Java Integration This code is testing a method which runs in the Netty framework which is, of course, written in Java. I like the safety Java gives me in the production code, but many of the things which are great about Java really suck for smaller things like Unit Tests
  6. Operator Overloading In Groovy, “==” calls “.equals”. Such a little thing but it makes the cognitive load so much lighter

As I alluded to, it isn’t all roses and puppies. When you mix duck typing with the implicit returns, you have to be careful if the method you are mocking returns type void. In this case you will get an exception unless you include an explicit return.

Overall this is a great example of what makes Groovy a “better Java”.