Created
April 7, 2017 15:34
-
-
Save westonal/1071a8a840cb05aaf84844e7424b7d1e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.redspace.NamedMonads | |
| import org.junit.Assert.assertEquals | |
| import org.junit.runner.RunWith | |
| @RunWith(SpecRunner::class) | |
| class CalculatorTestsUsingRunner { | |
| val givenCalculator = "calculator" sut given { | |
| Calculator() | |
| } | |
| val noop = "nothing" define { | |
| it: Calculator -> | |
| } | |
| fun press(key: Int) = "press $key" define { | |
| it: Calculator -> | |
| it.press(key) | |
| } | |
| fun press(key: Char) = "press '$key'" define { | |
| it: Calculator -> | |
| it.press(key) | |
| } | |
| fun reads(n: Int) = "reads $n" define { | |
| it: Calculator -> | |
| assertEquals(n, it.reads()) | |
| } | |
| @Spec | |
| fun `Zero at start`() = givenCalculator whenever noop then reads(0) | |
| @Spec | |
| fun `First digit press`() = givenCalculator whenever press(1) then reads(1) | |
| @Spec | |
| fun `Second digit press`() = givenCalculator given press(1) whenever press(2) then reads(12) | |
| @Spec | |
| fun `Add press doesn't clear`() = givenCalculator given press(1) whenever press('+') then reads(1) | |
| @Spec | |
| fun `Add before equals`() = givenCalculator given press(1) given press('+') whenever press(2) then reads(2) | |
| @Spec | |
| fun `One digit add`() = givenCalculator given press(1) given press('+') given press(2) whenever press('=') then reads(3) | |
| @Spec | |
| fun `Two digit add`() = givenCalculator given press(1) given press(2) given press('+') given press(3) given press(4) whenever press('=') then reads(12 + 34) | |
| } | |
| class Calculator { | |
| var buffer = 0 | |
| var display = 0 | |
| var clearNextPress = false | |
| var operation = ' ' | |
| fun press(i: Int) { | |
| if (clearNextPress) { | |
| display = 0 | |
| clearNextPress = false | |
| } | |
| display = display * 10 + i | |
| } | |
| fun reads(): Int { | |
| return display | |
| } | |
| fun press(operation: Char) { | |
| when (operation) { | |
| '+' -> { | |
| buffer = display | |
| this.operation = operation | |
| clearNextPress = true | |
| } | |
| '=' -> display += buffer | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment