Tuesday, February 22, 2011

JUnit 4 Scala

Having just tried the very basics of getting ScalaIDE up and running for Scala I naturally immediately want unit tests because like any good Java developer I believe my code doesn't work until proven otherwise.

The internets turned up a number of fairly ugly sounding solutions for getting unit testing going in Scala so I thought rather than try that, why not just see if I can use ye olde JUnit "just like Java" (does that make me a bad Scala user?). Scala compiles to normal .class files so provided I get both Scala and JUnit on classpath it should work just fine. And it does!

First I expressed my dependence on JUnit. As I'm using a simple Eclipse test project I just right-clicked the project, selected Build Path>Add Libraries, picked JUnit and then selected to use JUnit 4. This added the JUnit 4 entry to my .classpath for me:
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
 <classpathentry kind="src" path="src"/>
 <classpathentry kind="con" path="org.scala-ide.sdt.launching.SCALA_CONTAINER"/>
 <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
 <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
 <classpathentry kind="output" path="bin"/>
</classpath>

Next I created a test class, imported the bits of JUnit I needed, slapped @Test onto a few methods, held my breath, and hit Alt+Shift+X, T to run as JUnit test. And like magic it worked perfectly!

The code:
import org.junit.Assert._
import org.junit.Test

class FizzBuzzTestCase {
    @Test
    def meFail() = assertEquals(1, 2) 
 
    @Test
    def meSucceed() = assertEquals(1, 1)
}
The outcome:
Hooray! Super simple, familiar, and effective :)

2 comments:

Piotrek said...

Yes, that makes you a bad Scala user, I'm afraid.

The same thing that makes use use Scala instead of Java, should make you use Scala Test, Scala Check and Scala Specs. IMHO the last one is really powerfull and now I'm working on exactly opposite thing: testing Java from Scala. Results? More expressive, more flexible, smaller test cases. If you can, you should also read article about testing in Scala in Javamagazin (Feb 2011). The author points good reasons to write tests in Scala.

Beside that, you can always turn your tests written in Scala to behave like familiar JUnit.

Rod said...

Hahaha ... probably it does :) I certainly wouldn't go so far (yet) as to recommend that this as a best practice. For a Java dev I would contend it is very familiar, quick, and easy to get up and running - significant pros.

From what I've read (no time to try it yet) Scala Test (the example code for which looks *awesome*) and JUnit actually play nice together. I hope this is true, as much of our existing build and CI infrastructure supports JUnit not AFAIK anything Scala-specific out of the box. Ease of use and tried-and-true both earn points ;)

Post a Comment