There are multiple libraries and testing methodologies for Scala, but in this tutorial, we’ll demonstrate one popular option from the ScalaTest framework called FunSuite.
This assumes you know how to build a project in IntelliJ.
Setup
- Create an sbt project in IntelliJ.
- Add the ScalaTest dependency:
- Add the ScalaTest dependency to your
build.sbtfile:libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.19" % Test - If you get a notification “build.sbt was changed”, select auto-import.
- These two actions will cause
sbtto download the ScalaTest library. - Wait for the
sbtsync to finish; otherwise,AnyFunSuiteandtest()will be unrecognized.
- Add the ScalaTest dependency to your
- On the project pane on the left, expand
src=>main. - Right-click on
scalaand select New => Scala class. - Call it
CubeCalculator, change the Kind toobject, and hit enter or double-click onobject. - Replace the code with the following:
object CubeCalculator: def cube(x: Int) = x * x * x
Creating a test
- On the project pane on the left, expand
src=>test. - Right-click on
scalaand select New => Scala class. - Name the class
CubeCalculatorTestand hit enter or double-click onclass. - Replace the code with the following:
import org.scalatest.funsuite.AnyFunSuite class CubeCalculatorTest extends AnyFunSuite: test("CubeCalculator.cube") { assert(CubeCalculator.cube(3) === 27) } - In the source code, right-click
CubeCalculatorTestand select Run ‘CubeCalculatorTest’.
Understanding the code
Let’s go over this line by line:
class CubeCalculatorTestmeans we are testing the objectCubeCalculatorextends AnyFunSuitelets us use functionality of ScalaTest’s AnyFunSuite class such as thetestfunctiontestis a function that comes from the FunSuite library that collects results from assertions within the function body."CubeCalculator.cube"is a name for the test. You can call it anything but one convention is “ClassName.methodName”.asserttakes a boolean condition and determines whether the test passes or fails.CubeCalculator.cube(3) === 27checks whether the output of thecubefunction is indeed 27. The===is part of ScalaTest and provides clean error messages.
Adding another test case
- Add another
assertstatement after the first one that checks for the cube of0. - Re-run the test again by right-clicking
CubeCalculatorTestand selecting ‘Run CubeCalculatorTest’.
Conclusion
You’ve seen one way to test your Scala code. You can learn more about ScalaTest’s FunSuite on the official website.