Running ScalaTest unit tests in Eclipse

I do a lot of work from the command line with Ant builds and similar things, but there are times I like to do things through Eclipse. Today I wanted to run my ScalaTest unit tests in Eclipse, and found this to be a straightforward task.

Besides Scala, Eclipse, and an Eclipse project, you'll need:

Put those two jar files in your lib directory, add then add them to your build path.

To make sure everything works, you'll want to run a simple test. You can use the following Scala class (an object, actually) as a class to test. Just name it StringUtils.scala in your Scala/Eclipse project:

com.valleyprogramming.scalatest

object StringUtils {
  
  def splitCamelCase(s: String): String = {
   return s.replaceAll(
      String.format("%s|%s|%s",
         "(?<=[A-Z])(?=[A-Z][a-z])",
         "(?<=[^A-Z])(?=[A-Z])",
         "(?<=[A-Za-z])(?=[^A-Za-z])"
      ),
      " "
   ).replaceAll("  ", " ")
  }

}

And then you can use this as a simple ScalaTest test class. For the purposes of this exercise, just name it StringUtilsTest.scala, and put it in the same folder as the first file:

com.valleyprogramming.scalatest

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter

/**
 * Requires ScalaTest and JUnit4.
 */
@RunWith(classOf[JUnitRunner])
class StringUtilsTest extends FunSuite with BeforeAndAfter {
  
  test("splitCamelCase works on FooBarBaz") {
    val s = StringUtils.splitCamelCase("FooBarBaz")
    assert(s.equals("Foo Bar Baz"))
  }

  test("splitCamelCase works on a blank string") {
    val s = StringUtils.splitCamelCase("")
    assert(s.equals(""))
  }

  test("splitCamelCase fails with a null") {
    val e = intercept[NullPointerException] {
      val s = StringUtils.splitCamelCase(null)
    }
    assert(e != null)
  }

}

Note: I'm not using the ScalaTest BeforeAndAfter functionality in this example, but I left that in the code because I typically do use it.

Once you have the jar files in your lib directory, and these two Scala tests classes, you can run the StringUtilsTest class in Eclipse. With this class active in your Eclipse editor, click Run, then Run As..., and you should see the option to run this class as a Junit Test. When you run these tests, the Eclipse JUnit view should open up, and the tests should run successfully, giving you a "green bar".

Reporting live from sunny downtown Boulder, Colorado, I hope this tutorial on running ScalaTest unit tests with Eclipse has been helpful.