Skip to content

Instantly share code, notes, and snippets.

@ZakTaccardi
Last active October 6, 2019 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZakTaccardi/a40569243e942cff0d0cfd1eb7ebc1ff to your computer and use it in GitHub Desktop.
Save ZakTaccardi/a40569243e942cff0d0cfd1eb7ebc1ff to your computer and use it in GitHub Desktop.
Companion Code to - Writing Awesome Tests - https://medium.com/p/b271c7838344
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