我知道我可以通过修改testOptions在sbt中为测试阶段添加设置和清理代码,例如:
val embedMongoTestSettings: Seq[Setting[_]] = Seq(
testOptions in Test += Tests.Setup( () => createMongod()),
testOptions in Test += Tests.Cleanup( () => destroyMongod())
)
我遇到的问题是,这是基于每个项目完成的,然后为每个项目完成一次。因此,当我设置了一个多项目时,我会在这种情况下启动几个数据库(这将起作用,但这意味着我必须按项目端口配置等)。
在sbt中是否有办法确保某些步骤仅在每个测试阶段运行一次,无论是针对多个项目,一个项目还是单个测试用例?
我想的唯一方法就是在设置和清理部分自己管理并发,所以请保留一个全局计数器,检查它是第一个开始还是最后一个被拆除。
答案 0 :(得分:1)
我在sequencing tasks上写了一篇博文,您可能会觉得它很有用。
如果你想聚合测试并确保测试顺序,一个快速的方法就是制作一个自定义命令。以下定义了名为sts
的命令别名:
lazy val commonSettings = Seq(
scalaVersion := "2.11.4"
)
lazy val specs2Core = "org.specs2" %% "specs2-core" % "2.4.15"
val startTest = taskKey[Unit]("start test")
val stopTest = taskKey[Unit]("stop test")
lazy val root = (project in file(".")).
aggregate(app, webapp).
settings(commonSettings: _*).
settings(addCommandAlias("sts", ";startTest;test;stopTest"): _*).
settings(
startTest in ThisBuild := {
println("starting server...")
Thread.sleep(500)
},
stopTest in ThisBuild := {
println("stopping server...")
Thread.sleep(500)
}
)
lazy val app = (project in file("app")).
settings(commonSettings: _*).
settings(
libraryDependencies += specs2Core % Test
)
lazy val webapp = (project in file("webapp")).
settings(commonSettings: _*).
settings(
libraryDependencies += specs2Core % Test
)
您可以根据需要替换startTest in ThisBuild
和stopTest in ThisBuild
的实现。
通过在ThisBuild
级别定义这些设置,sts
命令应该在根级别和单个子项目级别都有效。
root> sts
starting server...
[success] Total time: 1 s, completed Jan 13, 2015 5:20:58 PM
[info] HelloWorldSpec
....
[info] Passed: Total 3, Failed 0, Errors 0, Passed 3
[success] Total time: 1 s, completed Jan 13, 2015 5:20:59 PM
stopping server...
[success] Total time: 1 s, completed Jan 13, 2015 5:20:59 PM
root> project app
[info] Set current project to app
app> sts
starting server...
[success] Total time: 1 s, completed Jan 13, 2015 5:21:15 PM
[info] HelloWorldSpec
....
[info] Passed: Total 3, Failed 0, Errors 0, Passed 3
[success] Total time: 1 s, completed Jan 13, 2015 5:21:16 PM
stopping server...
[success] Total time: 1 s, completed Jan 13, 2015 5:21:16 PM