在Scala中進行單元測試通常使用ScalaTest或JUnit。下面是一個簡單的示例:
sbt new sbt/scala-seed.g8
build.sbt
文件中添加ScalaTest依賴:libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.2" % "test"
Calculator.scala
:class Calculator {
def add(a: Int, b: Int): Int = a + b
}
CalculatorSpec.scala
:import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
class CalculatorSpec extends AnyFlatSpec with Matchers {
"Calculator" should "add two numbers" in {
val calculator = new Calculator()
val result = calculator.add(2, 3)
result shouldEqual 5
}
}
sbt test
以上示例演示了如何使用ScalaTest進行單元測試。您也可以使用JUnit等其他測試框架來編寫和運行單元測試。