在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等其他测试框架来编写和运行单元测试。