In order to be able to start writing a Scala unit test and compile Scala code into our Java project, we need to add a few dependencies and the scala-maven-plugin to the pom.xml
file. The dependencies are as follows:
<dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.10.0</version> </dependency>
<dependency> <groupId>org.scalatest</groupId> <artifactId>scalatest_2.10</artifactId> <version>2.0/version> <scope>test</scope> </dependency>
Assert
statements in our test case:<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
Concerning the scala-maven-plugin
, just add something similar to the following XML block to the <plugins>
section of your pom.xml
build file:
<plugin> <groupId>net.alchim31.maven</groupId> <artifactId>scala-maven-plugin</artifactId> <executions> <execution> <id>scala-compile-first</id> <phase>process-resources</phase> <goals> <goal>add-source</goal> <goal>compile</goal> </goals> </execution> <execution> <id>scala-test-compile</id> <phase>process-test-resources</phase> <goals> <goal>testCompile</goal> </goals> </execution> </executions> </plugin>
If we try to rerun the tests, this time our newly created Scala test will be picked up and executed, as shown in the following code snippet:
> mvn clean test ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.demo.sample.CustomerScalaTest getCustomerId Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec Running com.demo.sample.CustomerTest getCustomerId Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec Results : Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
A couple of observations are worth mentioning about the CustomerScalaTest.scala
class. They are as follows:
*
wildcard is replaced by the underscore, _
.With very few additions to the pom.xml
build file, we now have made a regular Java project Scala aware, which means that we can freely add Scala classes and invoke any Java library within them. This also means that as Java developers, we are now able to migrate or refactor only small parts of a project if it makes sense and progressively improve our codebase as we get more acquainted with the Scala constructs.
This approach of dealing with an existing Maven project is only one way of proceeding. In the next chapter, we will see some other approaches with a more radical change that involves the Scala's Simple Build Tool (SBT), an alternative to Maven builds.