Fizzbuzzing hangover

class Fizzbuzz {
  def fizzbuzz(n:Int) = (n % 3, n % 5) match {
      case (0,0) => 'fizzbuzz
      case (0,_) => 'fizz
      case (_,0) => 'buzz
      case _     => n
    }
}

a test

import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers

class FizzbuzzTest extends FlatSpec with ShouldMatchers {
  val fb = new Fizzbuzz

  "Fizzbuzz.fizzbuzz(number:Int)" should "return 'fizz if number % 3 == 0" in {
    fb.fizzbuzz(3) should equal ('fizz)
  }
  it should "return 'buzz if number % 5 == 0" in {
    fb.fizzbuzz(5) should equal ('buzz)
  }
  it should "return 'fizzbuzz if number % 5 and 3 == 0" in {
    fb.fizzbuzz(15) should equal ('fizzbuzz)
  }
  it should "return number if number % 5 && 3 != 0" in {
    fb.fizzbuzz(1) should equal (1)
  }
}

compile Fizzbuzz: scalac Fizzbuzz.scala
compile FizzbuzzTest: scalac -cp .:scalatest-1.7.2/scalatest-1.7.2.jar FizzbuzzTest.scala
run the test: scala -cp .:scalatest-1.7.2/scalatest-1.7.2.jar org.scalatest.tools.Runner -p . -o -s FizzbuzzTest

Run starting. Expected test count is: 4
FizzbuzzTest:
Fizzbuzz.fizzbuzz(number:Int) 
- should return 'fizz if a number % 3 == 0
- should return 'buzz if a number % 5 == 0
- should return 'fizzbuzz if a number % 5 and 3 == 0
- should return number if a number % 5 && 3 != 0
Run completed in 191 milliseconds.
Total number of tests run: 4
Suites: completed 1, aborted 0
Tests: succeeded 4, failed 0, ignored 0, pending 0
All tests passed.

If you don’t want to use the Runner then you can start a REPL with the -cp to include . and scalatest. Then in the REPL type: (new FizzbuzzTest).execute() … it should look like this:

scala> (new FizzbuzzTest).execute()
FizzbuzzTest:
Fizzbuzz.fizzbuzz(number:Int) 
- should return 'fizz if a number % 3 == 0
- should return 'buzz if a number % 5 == 0
- should return 'fizzbuzz if a number % 5 and 3 == 0
- should return number if a number % 5 && 3 != 0

Also, if you like beer, I suggest getting some Wheat beer from Camden town brewery.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s