Saturday, July 24, 2010

Scala Testing with Junit 4 and Annotations

JUnit annotations can easilty be used in Scala based tests just as they can in Java based tests.

The following is a basic scala test using the Junit annotations. For the sake of keeping the code as simple as possible we won't introduce thread safety into the example.


package com.foo
import org.junit.{Before, Test}
import org.junit.Assert.assertTrue

class BasicTest{
var bankAccount:BankAccount = _

@Before
def setup() = {bankAccount = new BankAccount(100)}

@Test
def addsCorrectly {
assertTrue(bankAccount.add(150) == 250)
}
}

class BankAccount(private var balance:Double){
def add(amt:Double):Double = { balance + amt }
}

As you can see, annotating JUnit tests in scala is pretty much the same as it is in java.
Except for some syntactical differences, handling tests that expect exceptions is also very similar to the way they are handled in java unit tests. Consider the following example:


package com.foo
import org.junit.Test
class FooTest{
@Test { val expected = classOf[ IllegalArgumentException] }
def shouldThrowException {
Foo.methodThatThrowsException
}
object Foo{
def methodThatThrowsException() = throw new IllegalArgumentException
}
}

One thing you may have noticed is that I declared a val in the annotation. Scala processes annotations in a different manner than Java. More on this can be found here.

No comments:

Post a Comment