我正在开发一个项目,其中运行一些测试的标准方法 foo 是执行 run foo --bar --baz --qux --quux someDirectory 。更糟糕的是,文档非常薄,需要仔细研究才能弄清楚测试是如何运行的。

出现这种情况的原因是该项目会生成一些代码(它生成 C++,然后编译并运行),并且测试是运行生成的代码与一个模型,该模型也是由生成的生成代码的 blob同一个项目。从这个角度来看,您可以看到事情是如何变成这样的,但它使运行测试变得不直观。

我希望能够使用 test foo 运行测试。是否可以让 test foo 简单地执行上面的运行命令,如果可以,我该怎么做?

如果不可能,我将添加一些文档,以便项目的新手可以更轻松地解决问题。但是,我更愿意使事情与其他使用 sbt 的项目保持一致。

最佳答案

目前最好的方法是直接实现自定义任务。有关详细信息,请参阅 Input Tasks

// A custom task is required because `test` doesn't accept input.
lazy val customTest = inputKey[Unit]("custom test")

// This custom parser accepts a space separated list of arguments and then appends
//   the fixed arguments to them.  To do further parsing based on the user-specified
//   arguments, use `flatMap` and return the next Parser.
lazy val testParser =
   Def.spaceDelimited().map( (explicitArgs: Seq[String]) =>
      explicitArgs ++ Seq("--bar", "--baz", "--qux", "--quux", "someDirectory")
   )

customTest := {
   // the result of parsing
   val args = testParser.parsed
   // auto-detected main class: can replace with literal string
   val main = (mainClass in Compile).value getOrElse error("No main class detected.")
   // main classpath, including compiled classes
   val classpath = (fullClasspath in Compile).value.files
   // provides Scala code execution
   val scalaRun = (runner in (Compile, run)).value
   val result = scalaRun.run(main, classpath, args, streams.value.log)
   // handle any error
   result foreach { errorMsg => sys.error(errorMsg) }
}

关于scala - 您如何使 sbt `test` 等效于带有一组选项的运行命令?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19065391/

10-11 22:30
查看更多