Skip to content

Instantly share code, notes, and snippets.

@jzallas
Last active October 25, 2021 22:38
Show Gist options
  • Save jzallas/a0a4867a978c5b53d728807fdc7c70e0 to your computer and use it in GitHub Desktop.
Save jzallas/a0a4867a978c5b53d728807fdc7c70e0 to your computer and use it in GitHub Desktop.
Using argument captors
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
import org.mockito.kotlin.*
class RepositoryImplTest {
@Test
fun `without validating prefix`() {
// setup
val mockApi: Api = mock()
val repository = RepositoryImpl("TEST", mockApi)
var result: String? = null
val onResult: Callback = { result = it }
// test
repository.fetch("foo", onResult)
// verify
verify(mockApi).fetch(eq("foo"), any())
// but how do we assert the prefix was used correctly ???
}
@Test
fun `validating prefix using a fake`() {
// setup
class FakeApi : Api {
lateinit var data: String
lateinit var onResult: Callback
override fun fetch(data: String, onResult: Callback) {
this.data = data
this.onResult = onResult
}
}
val fakeApi = FakeApi()
val repository = RepositoryImpl("TEST", fakeApi)
var result: String? = null
val onResult: Callback = { result = it }
// test
repository.fetch("foo", onResult)
// verify
assertEquals("foo", fakeApi.data)
fakeApi.onResult.invoke("bar")
assertNotNull(result)
assertEquals("[TEST] bar", result)
}
@Test
fun `validating prefix using a captor`() {
// setup
val mockApi: Api = mock()
val repository = RepositoryImpl("TEST", mockApi)
val captor = argumentCaptor<Callback>()
var result: String? = null
val onResult: Callback = { result = it }
// test
repository.fetch("foo", onResult)
// verify
verify(mockApi).fetch(eq("foo"), captor.capture())
val callback = captor.firstValue
callback.invoke("bar")
assertNotNull(result)
assertEquals("[TEST] bar", result)
}
@Test
fun `validating prefix using an inline captor`() {
// setup
val mockApi: Api = mock()
val repository = RepositoryImpl("TEST", mockApi)
var result: String? = null
val onResult: Callback = { result = it }
// test
repository.fetch("foo", onResult)
// verify
val captor = argumentCaptor<Callback> {
verify(mockApi).fetch(eq("foo"), capture())
}
val callback = captor.firstValue
callback.invoke("bar")
assertNotNull(result)
assertEquals("[TEST] bar", result)
}
}
typealias Callback = (String) -> Unit
interface Repository {
fun fetch(data: String, onResult: Callback)
}
class RepositoryImpl(private val prefix: String, private val api: Api) : Repository {
override fun fetch(data: String, onResult: Callback) {
api.fetch(data) { onResult.invoke("[$prefix] $it") }
}
}
interface Api {
fun fetch(data: String, onResult: Callback)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment