Last active
October 6, 2019 19:49
-
-
Save ZakTaccardi/a40569243e942cff0d0cfd1eb7ebc1ff to your computer and use it in GitHub Desktop.
Companion Code to - Writing Awesome Tests - https://medium.com/p/b271c7838344
This file contains 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
import org.assertj.core.api.Assertions | |
import org.junit.Before | |
import org.junit.Test | |
// function to test | |
fun Int.add(valueToAdd: Int): Int = this + valueToAdd | |
class AddTest { | |
private lateinit var test: TestDelegate | |
@Before | |
fun setUp() { | |
test = TestDelegate() | |
} | |
@Test | |
fun `2 plus 5 is 7`() { | |
test.given(initialValue = 2) | |
.whenValueIsAdded(5) | |
.thenSumIs(7) | |
} | |
@Test | |
fun `-1 plus 3 is 2`() { | |
test.given(initialValue = -1) | |
.whenValueIsAdded(3) | |
.thenSumIs(2) | |
} | |
@Test | |
fun `2 plus 5 is 7 - structured`() = addTest( | |
givenInitialValue = 2, | |
whenValueIsAdded = 5, | |
thenSumIs = 7 | |
) | |
@Test | |
fun `-1 plus 3 is 2 - structured`() = addTest( | |
givenInitialValue = -1, | |
whenValueIsAdded = 3, | |
thenSumIs = 2 | |
) | |
private fun addTest( | |
givenInitialValue: Int, | |
whenValueIsAdded: Int, | |
thenSumIs: Int | |
) { | |
test.given(givenInitialValue) | |
.whenValueIsAdded(whenValueIsAdded) | |
.thenSumIs(thenSumIs) | |
} | |
private class TestDelegate(scope: CoroutineScope): CoroutineScope by scope { | |
private var initialValue: Int? = null | |
private var valueToAdd: Int? = null | |
private var actualSum: Int? = null | |
fun given(initialValue: Int) = apply { | |
this.initialValue = initialValue | |
} | |
fun whenValueIsAdded(valueToAdd: Int) = apply { | |
this.valueToAdd = valueToAdd | |
// this is the function we are testing | |
actualSum = initialValue!!.add(this.valueToAdd!!) | |
} | |
fun thenSumIs(expected: Int) = apply { | |
Assertions.assertThat(actualSum) | |
.describedAs("Adding $initialValue and $valueToAdd should produce $expected, but it produced $actualSum") | |
.isEqualTo(expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment