2

假设我在 main/scala 中有一个 scalatest 类,比如

import org.scalatest.FunSuite

class q3 extends FunSuite {
    test("6 5 4 3 2 1") {
        val digits = Array(6,5,4,3,2,1)
        assert(digits.sorted === Array(1,2,3,4,5,6))
    }
}

如何使用 sbt 运行它?

我试过了sbt test,他们都有像这样的输出sbt testOnlysbt "testOnly *q3"

[info] Run completed in 44 milliseconds.
[info] Total number of tests run: 0
[info] Suites: completed 0, aborted 0
[info] Tests: succeeded 0, failed 0, canceled 0, ignored 0, pending 0
[info] No tests were executed.
[info] No tests to run for Test / testOnly

几年前的一个类似问题说他们成功使用了testOnly,但我无法让它工作。

VSCode 上的金属扩展在文件打开时显示一个“测试”链接,该链接成功运行测试,但没有显示它是如何做到的。我想知道如何通过 sbt 做到这一点。

4

1 回答 1

3

像这样将ScalaTest放在Compile类路径中build.sbt

libraryDependencies += "org.scalatest" %% "scalatest" % "3.1.0"

然后org.scalatest.run从 中显式调用 runner App,例如,

object MainTests extends App {
  org.scalatest.run(new ExampleSpec)
}

把它放在一起,我们有src/main/scala/example/MainTests.scala

package example

import org.scalatest.matchers.should.Matchers
import org.scalatest.flatspec.AnyFlatSpec
import collection.mutable.Stack
import org.scalatest._

class ExampleSpec extends AnyFlatSpec with Matchers {
  "A Stack" should "pop values in last-in-first-out order" in {
    val stack = new Stack[Int]
    stack.push(1)
    stack.push(2)
    stack.pop() should be (2)
    stack.pop() should be (1)
  }
}

object MainTests extends App {
  org.scalatest.run(new ExampleSpec)
}

并运行它runMain example.MainTests。此外,我们可以像这样Suites收集测试execute

class ExampleASpec extends FlatSpec with Matchers {
  "ExampleA" should "run" in { succeed }
}
class ExampleBSpec extends FlatSpec with Matchers {
  "ExampleB" should "run" in { succeed }
}

class ExampleSuite extends Suites(
  new ExampleASpec,
  new ExampleBSpec,
)

object MainTests extends App {
  (new ExampleSuite).execute()
}
于 2020-02-06T22:08:55.757 回答