The day started out cloudly and with a lot of rain. Fortunately the rain stopped during the day and for the next few days it should stay dry. This makes the walks to and from the hotel more comfortable. After registration there was some sweet pastry and drinks. For me the day started with presenting Getting Groovy, a beginner workshop for working with Groovy. It was nice to see people get there first contact with Groovy through Gradle and Spock on their Java projects. The presentation and notes are available online.
Suppose we will fetch some Amazon AWS news into a MongoDB database. These few lines made it possible with the use of Groovy and the Gmongo module:
One of the nice things about MongoDB is that documents are returned in JSON format.
If you use the Mongo-GORM plugin, however, the driver conveniently converts the returned results into a Grails domain class instance. You then have to serialize this domain class to get a JSON result back.
My colleague Arthur Arts has written a blog post Tasty Test Tip: Using ArgumentCaptor for generic collections with Mockito. This inspired me to do the same in Spock. With the ArgumentCaptor in Mockito the parameters of a method call to a mock are captured and can be verified with assertions. In Spock we can also get a hold on the arguments that are passed to method call of a mock and we can write assertions to check the parameters for certain conditions.
In Grails we can write unit tests for controllers. We can check for example the results from a
render() method. To check the result from a
forward() action we can use the
forwardedUrl property of the mock response object. The format of the URL is very basic and has the following form:
/grails/(controller)/(action).dispatch?(queryParameters). So we get the servlet representation of a Grails controller request. We can use this format to check if our
forward() method is correct in the unit test.
Unit testing tag libraries in Grails is easy. We can use the
applyTemplate() method to execute a tag and check the output. We pass the HTML string representing the tag to
applyTemplate() as we would use it in a GSP. Attribute values of a tag can be String values, but also any other type. To pass other types in our test as attribute values we must add an extra argument to
applyTemplate(). The argument is a
Map with model values which are used to pass as value to the tag library attributes.