Thursday, May 3, 2007

Unit Testing with Groovy




So we know what the Groovy is and how to eat it. Now it is time to do something useful in terms of methodology. I'm agilist and the thing that I do after knowing constructors and reductors is how to test it. Again Groovy is really helpful, and easy to use. So, you don't need to add additional libraries or do some hacking to use tests in Groovy - they are provided in a default installation. By the default installation i mean get a Groovy from local ftp untar it and there it is ready to be used. So here is a simple example:

Create a class Square.groovy

class Square{
def square(x) {x*x}
}


Create a class SquareTest.groovy

import Square

class SquareTest extends GroovyTestCase{

void testSquare(){
Square square = new Square()
assertEquals( square.square(3),9)
}
}


be sure that both classes are in one catalog. In a command line just type:

groovy SquareTest.groovy


and see the result - everything is fine. It is the easiest xUnit framework that I've seen.
One thing about classes in Groovy - they are public by default, same as methods.

Now let's say that we want to create a framework in maven or we already have one and we want to add some Groovy classes or Groovy test classes. This task is more complicated - because of maven, it is a good tool but sometimes when you search in a xml files for a bug it it terrible, I hate it, but again it is like 200 times better then ant.

so to create a maven project (I'm using maven 2.*) just type:

mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-app


Now goto my-app and edit pom.xml add:

<dependency>
<groupid>groovy</groupid>
<artifactid>groovy-all</artifactid>
<version>1.0</version>
<scope>test</scope>
</dependency>


create a folder groovy in my-app/src/main directory and in the my-app/src/test. In other words just in this same place as java folder. And put a *.groovy class there. Go back to the my-app directory, and run:

mvn groovy:compile


to compile main classes.

mvn groovy:testCompile


to compile test classes.

You might ask "Cool, but is there a way to compile classes just by calling normal mvn install or mvn compile?". Yes there is, just add this code to your pom.xml file:


<build>
<plugins>
<plugin>
<groupid>org.codehaus.mojo</groupid>
<artifactid>groovy-maven-plugin</artifactid>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>


Now every time you compile or run tests also groovy classes are going to be included.

No comments: