Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing additional arguments to tests with ScalaTest

Currently I'm using IntelliJ Idea 15 and Scalatest framework to make some unit tests. And I need to pass my own arguments into test and somehow read them from code. For instance: Suppose I have such class

class Test extends FunSuite {
   test("Some test") {
       val arg = // here I want to get an argument which I want to pass. Something like args("arg_name")
       println(arg)
       assert(2 == 2)
   }
}

And to run the test with argument I want to do something like

test -arg_name=blabla

So, the question is how to pass this an argument and how to obtain it.

like image 608
alex Avatar asked Feb 16 '16 12:02

alex


2 Answers

I found interesting trait BeforeAndAfterAllConfigMap. This one has beforeAll method with a parameter configMap: ConfigMap. So here is my solution:

class Test extends FunSuite with BeforeAndAfterAllConfigMap {

  override def beforeAll(configMap: ConfigMap) = {
    //here will be some stuff and all args are available in configMap
  }

  test("Some test") {
    val arg = // here I want to get an argument which I want to pass. Something like args("arg_name")
    println(arg)
    assert(2 == 2)
  }
}
like image 95
alex Avatar answered Oct 13 '22 12:10

alex


In scalatest, we can use configMap to pass command parameters.

There is an example with using configMap:

import org.scalatest.{ConfigMap, fixture}

class TestSuite extends fixture.Suite with fixture.ConfigMapFixture{
  def testConfigMap(configMap: Map[String, Any]) {
    println(configMap.get("foo"))
    assert(configMap.get("foo").isDefined)
  }
}

object Test {
  def main(args: Array[String]): Unit = {
    (new TestSuite).execute(configMap = ConfigMap.apply(("foo","bar")))
  }
}

also we can run test with command line parameters:

scala -classpath scalatest-<version>.jar org.scalatest.tools.Runner -R compiled_tests -Dfoo=bar

scalatest runner ConfigMapFixture Test

like image 42
chengpohi Avatar answered Oct 13 '22 11:10

chengpohi