在Scala中進(jìn)行單元測(cè)試通常使用ScalaTest或JUnit。下面是一個(gè)簡(jiǎn)單的示例:
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進(jìn)行單元測(cè)試。您也可以使用JUnit等其他測(cè)試框架來編寫和運(yùn)行單元測(cè)試。