Sbt 运行 从 src/main/scala 而不是 src/test/scala 测试?

Sbt run tests from src/main/scala instead of src/test/scala?

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

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 testsbt 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 上的金属扩展名在文件打开时显示 "test" link,成功 运行 测试,但没有显示它是如何工作的那。我想知道如何通过sbt来完成。

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

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

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

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

Putting it together 我们在 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 and 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()
}