Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the ScalaTest BDD syntax in a JUnit environment?

I would like to describe tests in BDD style e.g. with FlatSpec but keep JUnit as a test runner.

The ScalaTest Quick Start does not seem to show any example of this:

http://www.scalatest.org/getting_started_with_junit_4

I first tried naively to write tests within @Test methods, but that doesn't work and the assertion is never tested:

@Test def foobarBDDStyle {
    "The first name control" must "be valid" in {
        assert(isValid("name·1"))
    }
    // etc.
}

Is there any way to achieve this? It would be even better if regular tests can be mixed and matched with BDD-style tests.

like image 664
ebruchez Avatar asked Jan 02 '11 20:01

ebruchez


2 Answers

The way you probably want to do that is to use the @RunWith annotation, like this:

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec

@RunWith(classOf[JUnitRunner])
 class MySuite extends FlatSpec {
   "The first name control" must "be valid" in {
        assert(isValid("name·1"))
    }
 }

JUnit 4 will use ScalaTest's JUnitRunner to run the FlatSpec as a JUnit test suite.

like image 108
Bill Venners Avatar answered Oct 29 '22 05:10

Bill Venners


You don't need to have defs and @Test annotations. Here is an example:

import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.junit.ShouldMatchersForJUnit

@RunWith(classOf[JUnitRunner])
class SpelHelperSpec extends FlatSpec with ShouldMatchersForJUnit {

  "SpelHelper" should "register and evaluate functions " in {
    new SpelHelper()
      .registerFunctionsFromClass(classOf[Functions])
      .evalExpression(
        "#test('check')", new {}, classOf[String]) should equal ("check")
  }

  it should "not register non public methods " in {
    val spelHelper = new SpelHelper()
      .registerFunctionsFromClass(classOf[Functions])
    evaluating { spelHelper.evalExpression("#testNonPublic('check')",
      new {}, classOf[String]) } should produce [SpelEvaluationException]
  }
}

Source

like image 22
Abhinav Sarkar Avatar answered Oct 29 '22 06:10

Abhinav Sarkar