目前我正在使用IntelliJ Idea 15和Scalatest框架进行一些单元测试。我需要将自己的参数传递给测试,并以某种方式从代码中读取它们。例如: 假设我有这样的课程
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)
}
}
要使用参数运行测试,我想做类似
的操作test -arg_name=blabla
所以,问题是如何传递这个参数以及如何获得它。
答案 0 :(得分:7)
在 scalatest 中,我们可以使用configMap来传递命令参数。
使用 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")))
}
}
我们也可以使用命令行参数运行测试:
scala -classpath scalatest-<version>.jar org.scalatest.tools.Runner -R compiled_tests -Dfoo=bar
答案 1 :(得分:6)
我发现了有趣的特征BeforeAndAfterAllConfigMap。这个有一个带有参数configMap:ConfigMap的beforeAll方法。所以这是我的解决方案:
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)
}
}
答案 2 :(得分:0)
如果您已经使用FunSpec,FunSuite或FlatSpec,我发现 BeforeAndAfterAllConfigMap 可以轻松地并入现有的scalatest中。您要做的就是使用 BeforeAndAfterAllConfigMap 导入并扩展测试。
可以将参数传递给scalatest的方法之一是:
这是FlatSpec中的完整示例,但也很容易在FunSuite中应用:
package com.passarg.test
import org.scalatest.{BeforeAndAfterAllConfigMap, ConfigMap, FlatSpec}
class PassArgsToScala extends FlatSpec with BeforeAndAfterAllConfigMap {
var foo = ""
override def beforeAll(configMap: ConfigMap) = {
// foo=bar is expected to be passed as argument
if (configMap.get("foo").isDefined) {
foo = configMap.get("foo").fold("")(_.toString)
}
println("foo=" + foo)
}
"Arg passed" must "be bar" in {
assert(foo === "bar")
info("passing arg seem to work ==> " + "foo=" + foo)
}
}
build.gradle
apply plugin: 'scala'
repositories {
mavenCentral()
}
dependencies {
compile 'org.scala-lang:scala-library:2.11.8'
testCompile 'org.scalatest:scalatest_2.11:3.0.0'
}
task spec(dependsOn: ['testClasses']) {
javaexec {
main = 'org.scalatest.tools.Runner'
args = ['-R', 'build/classes/test', '-o']
args += '-m'
args += 'com.passarg.test'
if (project.hasProperty("foo")) {
args += "-Dfoo=" + project.foo
}
classpath = sourceSets.test.runtimeClasspath
}
}
从命令行运行测试:
./gradlew -q spec -Pfoo=bar
结果:
$ ./gradlew -q spec -Pfoo=bar
...
Run starting. Expected test count is: 1
PassArgsToScala:
Arg passed
- must be bar
+ passing arg seem to work ==> foo=bar