Tuesday, September 6, 2011

Test driven development with Maven and Scala

As projects grow on size and complexity, you can feel a little lost on every issue or bug to fix.
It's very common to fix a bug today and, after few months when project needs to meet one more requirement (due to the fantasy of the customer or of the developer himself...), encouter the same problem once again. It's called "regression".
To avoid this unpleasant situation, you can rely on some tools to perform automatic tests: Java provides JUnit (I use JUnit4) and Scala provides Scalatest.
Obviously you can run the tests invoking the correct tool by command-line, but with Maven you can integrate all the phases of the compilation-testing task in order to have your project compiled and tested (and eventually also deployed to a repo) with one single command.
To do so, you'll have to change a little bit your POM file.
You'll also need to write your tests in the correct manner, but there are official example from the Scalatest team linked at the end of the article.

POM modifications
First add some repository...
  <name>Scala-Tools Maven2 Repository</name>

  <name>Scala-Tools Maven2 Repository</name>
Now, the dependencies. You must add the dependency
I assume you set a property named scala.version valued with the Scala version you are using. Please note the version of this artifact vary with Scala version. I'm using the 2.9.0-1 version of Scala: if you are using another version, check the repo http://scala-tools.org/repo-releases
Optionally, you can remove the dependency
Then jump to the build section.
Last thing to do: add the Surfire plugin. Add in the root:
Wow! Now you are ready to start writing your tests!

How to write tests
Writing tests using JUnit3
Writing tests using JUnit4
Writing tests using Scalatest FunSuite features
Writing tests using Scalatest Spec features

Executing the tests
Maven will execute these tests whenever you compile, deploy or simply test your projects.
Be carefull to clean your project always before compiling or testing.
For example, the command line to launch tests only (obviously, the project will be compiled too) is
mvn clean test
from the folder containing the POM.xml of your project

Hope you'll find usefull,

No comments:

Post a Comment