Spock has some great features to write specifications or tests that are short and compact. One of them is the old()
method. The old()
method can only be used in a then:
block. With this method we get the value a statement had before the when:
block is executed.
Let's see this with a simple example. In the following specification we create a StringBuilder
with an initial value. In the then:
block we use the same initial value for the assertion:
Continue reading →
There is really no excuse to not write unit tests in Grails. The support for writing tests is excellent, also for testing code that has to deal with the locale set in a user's request. For example we could have a controller or taglib that needs to access the locale. In a unit test we can invoke the addPreferredLocale()
method on the mocked request object and assign a locale. The code under test uses the custom locale we set via this method.
In the following controller we create a NumberFormat
object based on the locale in the request.
Continue reading →
Grails adds a couple of methods and properties to our controller classes automatically. One of the methods is the header()
method. With this method we can set a response header with a name and value. The methods accepts two arguments: the first argument is the header name and the second argument is the header value.
In the following controller we invoke the header()
method to set the header X-Powered-By
with the Grails and Groovy version.
Continue reading →
NOTE: this blog post was written for version 0.8 of the Karma test runner. An updated blog post for the new Karma 0.10 can be found here.
For my current project we are using Maven to build our AngularJS application. Furthermore we use Sonar (recently renamed to SonarCube) to monitor our code standards / best practices and unit test coverage. In this blog post we describe how to integrate the Karma (Testacular) test runner with Maven and how to add your AngularJS (or any JavaScript) application to SonarQube.
Continue reading →
When we want to clone an object there are several ways to do this For instance we can implement Clonable, which makes it possible to duplicate an object. We also can create a new object manually by calling each setter or use a parameterised constructor. In case we want to clone a Hibernate object, there is an extra option available which is more elegant: the Hibernate3BeanReplicator. The Hibernate3BeanReplicator is provided by Beanlib (http://beanlib.sourceforge.net/) and it supports deep clones, so we can also clone related one-to-one objects easily. For example we want to clone the Student object, including all child (one-to-one) objects.
Student student = studentDao.getStudentById(1);
HibernateBeanReplicator replicator = new Hibernate3BeanReplicator();
Student studentCopy = replicator.deepCopy(student);
studentCopy.setId(null);
studentCopy.getRelatedObject().setId(null);
studentDao.save(studentCopy);
Continue reading →