FunSuite

Using AnyFunSuite with ScalaTest allows for writing tests in a very flexible and straightforward way, combining the benefits of specification and testing. Let's apply this to a Calculator example, focusing on creating a suite of tests to verify its functionality.

Step 1: Implement the Calculator

Create a simple Calculator object with basic arithmetic operations. Place this in your src/main/scala directory if you're following standard Scala project structure.

object Calculator:
  def add(a: Int, b: Int): Int = a + b
  def subtract(a: Int, b: Int): Int = a - b
  def multiply(a: Int, b: Int): Int = a * b
  def divide(a: Int, b: Int): Option[Int] = if (b == 0) None else Some(a / b)

Step 2: Set Up ScalaTest Dependency

Make sure ScalaTest is included in your build.sbt:

libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.9" % Test

Step 3: Write Tests Using AnyFunSuite

Now, create a test class for the Calculator using AnyFunSuite. This class should be in the src/test/scala directory.

import org.scalatest.funsuite.AnyFunSuite

class CalculatorTest extends AnyFunSuite:

  test("Calculator.add should return the sum of two numbers") 
    assert(Calculator.add(1, 2) === 3)

  test("Calculator.subtract should return the difference of two numbers") 
    assert(Calculator.subtract(5, 3) === 2)

  test("Calculator.multiply should return the product of two numbers") 
    assert(Calculator.multiply(4, 3) === 12)

  test("Calculator.divide should return the quotient of two numbers") 
    assert(Calculator.divide(10, 2) === Some(5))

  test("Calculator.divide should return None when dividing by zero") 
    assert(Calculator.divide(5, 0) === None)

Step 4: Running Tests

To run your tests, use sbt from the command line in your project root:

sbt test

This command will execute all tests in your project, including the CalculatorTest suite you just defined.

Understanding the Test Code