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.sbt
file:libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.8" % Test
- If you get a notification “build.sbt was changed”, select auto-import.
- These two actions will cause
sbt
to download the ScalaTest library. - Wait for the
sbt
sync to finish; otherwise,FunSuite
andtest()
will be unrecognized.
- Add the ScalaTest dependency to your
- On the project pane on the left, expand
src
=>main
. - Right-click on
scala
and select New => Scala class. - Call it
CubeCalculator
, change the Kind toobject
, and click OK. - Replace the code with the following:
object CubeCalculator extends App { def cube(x: Int) = { x * x * x } }
Creating a test #
- On the project pane on the left, expand
src
=>test
. - Right-click on
scala
and select New => Scala class. - Name the class
CubeCalculatorTest
and click OK. - Replace the code with the following:
import org.scalatest.FunSuite class CubeCalculatorTest extends FunSuite { test("CubeCalculator.cube") { assert(CubeCalculator.cube(3) === 27) } }
- In the source code, right-click
CubeCalculatorTest
and select Run ‘CubeCalculatorTest’.
Understanding the code #
Let’s go over this line by line:
class CubeCalculatorTest
means we are testing the objectCubeCalculator
extends FunSuite
lets us use functionality of ScalaTest’s FunSuite class such as thetest
functiontest
is 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”.assert
takes a boolean condition and determines whether the test passes or fails.CubeCalculator.cube(3) === 27
checks whether the output of thecube
function is indeed 27. The===
is part of ScalaTest and provides clean error messages.
Adding another test case #
- Add another
assert
statement after the first one that checks for the cube of0
. - Re-run the test again by right-clicking
CubeCalculatorTest
and 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.