What I can't understand is why we keep using java to write unit tests when we have some awesome languages like groovy and scala.
To that goal, I am going to write a couple of articles to help you start using them today. That's right, don't wait till tomorrow. Just do it for your finger tips' sake.
Will start with groovy. Our build tool will be maven, not my favourite, simply the most popular.
Also, I will be using eclipse. I did not bother using m2eclipse.
The base projectWill start creating a new service project using maven archetypes:
Unfortunately I could not get maven to generate a proper eclipse .classpath file for groovy files.
mvn archetype:generate -DgroupId=info.devinprogress -DartifactId=PostService -DarchetypeArtifactId=spring-data-basic -DarchetypeGroupId=com.cloudfoundry.tothought -DinteractiveMode=false //Generate the eclipse project files mvn eclipse:eclipse
After trying to tweak the maven-compiler plugin and then using the build-helper-maven-plugin eventually I gave up and had to manually change the eclipse
If you get it working well, let me know. Otherwise add this line to the .classpath file.
<classpathentry including="**/*.groovy" kind="src" output="target/test-classes" path="src/test/groovy"/>
Add the groovy source code to your maven buildWe need to tell maven we also have some groovy files to be compiled. To do that we'll change the build step and add the groovy compiler.
<build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <compilerId>groovy-eclipse-compiler</compilerId> <source>1.7</source> <target>1.7</target> </configuration> <dependencies> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-eclipse-compiler</artifactId> <version>2.7.0-01</version> </dependency> </dependencies> </plugin> </plugins> </build>Also you'll need the groovy dependency added for your test scope.
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>2.1.0</version> <scope>test</scope> </dependency>
Install groovy pluginThe groovy plugin will help when creating a new groovy class. It comes with code completion, syntax highlight and all those nice things. But probably most importantly it will compile your groovy files to bytecode. That will be handy when running test units from your IDE.
You can get the update site for your eclipse version here
Make sure you pick the features as shown in the screenshot below:
Once you install it, restart eclipse. Right click on the project and add the groovy nature.
You are ready to testCreate a new folder src/test/groovy and add all your groovy tests in there. To run the in eclipse make sure you select the class in the explorer and not the file, like shown in the screenshot below.
You are ready to test and roll.
Check the project on github.
Next post we'll right some more unit test for the PostRepository taking advantage of the groovy features.