Skip to content

Instantly share code, notes, and snippets.

@ZakTaccardi
Created October 6, 2019 19:54
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/14a38290a90f4f65ed78820fc4fad226 to your computer and use it in GitHub Desktop.
Save ZakTaccardi/14a38290a90f4f65ed78820fc4fad226 to your computer and use it in GitHub Desktop.
Companion Code to - Writing Awesome Tests (Coroutine Edition)
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.withContext
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
// function to test
suspend fun Int.add(valueToAdd: Int): Int = withContext(Dispatchers.Default) {
// pretend this is an expensive operation, so we switch off the main thread
this@add + valueToAdd
}
class AddTest {
@Test
fun `2 plus 5 is 7`() = addTest {
given(initialValue = 2)
whenValueIsAdded(5)
thenSumIs(7)
}
@Test
fun `-1 plus 3 is 2`() = addTest {
given(initialValue = -1)
whenValueIsAdded(3)
thenSumIs(2)
}
private fun addTest(testBlock: suspend TestDelegate.() -> Unit) {
runBlockingTest {
val testDelegate = TestDelegate(this@runBlockingTest)
// invoke the testBlock with the `TestDelegate` as its receiver
testBlock(testDelegate)
}
}
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) {
this.initialValue = initialValue
}
suspend fun whenValueIsAdded(valueToAdd: Int) {
this.valueToAdd = valueToAdd
// this is the function we are testing
actualSum = initialValue!!.add(this.valueToAdd!!)
}
fun thenSumIs(expected: Int) {
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