Monday, November 16, 2009

ScalaTest BDD testing DSL

This is the first of three topics exploring some of the testing tools that you can use with Scala. They all integrate with JUnit and can be used with maven and ant.

The first example is ScalaTest. ScalaTest provides many different usage patterns but the one I will show today is a Behaviour Driven Design test. It provides a DSL for declaring a test that is nearly english in syntax and if done correctly can be given to a non technical person to review. The ScalaTest BDD test style was inspired by the work done on Specs by Eric Torreborre. I will demonstrate that library in the next topic.

I want to reiterate that ScalaTest permits several different styles of test writing. NUnit, JUnit and BDD are the main styles. So anyone that is used to NUnit or JUnit should have no problem using ScalaTest but if you like the look of the BDD test specifications then you can migrate and slowly become accustomed to that style.

If you want to integrate with JUnit one easy way to add the @RunWith annotation for the class. See JUnitRunner for details:
  1. import org.scalatest.junit.JUnitRunner
  2. import org.junit.runner.RunWith
  3. @RunWith(classOf[JUnitRunner])
  4. class StackSpec extends WordSpec {
  5. ...
  6. }

Instructions to run example:
  1. Download ScalaTest: http://www.scalatest.org/download
  2. Extract archive. For example to /tmp/
  3. Run scala with the ScalaTest jar on classpath: scala -classpath /tmp/scalatest-1.0/scalatest-1.0.jar
  4. copy in code

This example is directly taken from the ScalaTest documentation. It tests a Stack implementation.
  1. scala>  import org.scalatest.WordSpec
  2. import org.scalatest.WordSpec
  3. scala>  import scala.collection.mutable.Stack
  4. import scala.collection.mutable.Stack
  5. scala> 
  6. scala>  class StackSpec extends WordSpec {
  7.      | 
  8.      |    "A Stack" should {
  9.      | 
  10.      |      "pop values in last-in-first-out order" in {
  11.      |        val stack = new Stack[Int]
  12.      |        stack.push(1)
  13.      |        stack.push(2)
  14.      |        assert(stack.pop() === 2)
  15.      |        assert(stack.pop() === 1)
  16.      |      }
  17.      | 
  18.      |      "throw NoSuchElementException if an empty stack is popped" in {
  19.      |        val emptyStack = new Stack[String]
  20.      |        intercept[NoSuchElementException] {
  21.      |          emptyStack.pop()
  22.      |        }
  23.      |      }
  24.      |    }
  25.      |  }
  26. defined class StackSpec
  27. scala> new StackSpec().execute()
  28. A Stack 
  29. - should pop values in last-in-first-out order
  30. - should throw NoSuchElementException if an empty stack is popped

1 comment:

  1. Merci pour logiciel et pour les informations


    Si tu veux telecharger des logiciels gratuit free ICIIII


    Et pour telecharger la meilleure version de logiciel test adsl

    ReplyDelete