with JUnit (4), Is there an uncomplicated way to t...
# announcements
i
with JUnit (4), Is there an uncomplicated way to test that a callback was called (ideally without mockito or any other 3d party)? E.g. in Swift you can declare an "expectation" at the beginning of the test, call
waitForExpectations(timeout: 5, handler: *nil*)
at the end, and in the callback
expectation.fullfill()
to have the test wait for the callback
c
You’re probably best off running the test as a coroutine with
runBlocking
, which allows you to wrap the async call with
suspendCancelableCoroutine
and await for the result. Something like:
Copy code
@Test
fun test1() = runBlocking {
    val underTest = ServiceUnderTest()
    val result = suspendCancellableCoroutine<String> { continuation ->
        underTest.makeCall { continuation.resume(it) }
    }

    assertEquals("expectedValue", result)
}
e
It is simpler with a job:
Copy code
val event = Job()
event.complete() // to fire it
event.await() // to await for it
i
@elizarov should have mentioned that I'm using Android / JVM 1.6, sorry 😞
@Casey Brooks any idea why this hangs? The "!!! logged: $foo" shows up in the console but not "!!! doesn't execute this"
Copy code
@Test
fun testCallCallback() = runBlocking {
    val n = NativeApi()

    val result = suspendCancellableCoroutine<String> { continuation ->
        n.callCallback(object: Callback() {
            override fun log(foo: String) {
                println("!!! logged: $foo")
                continuation.resume(foo, onCancellation = {})
            }
        })
    }
    println("!!! doesn't execute this")
    assertEquals(result, "hi!")
}
actually, it does show up 🤔
the test actually is executed correctly and passes, but the green line stays in the middle and it shows a progress indicator, as if it was still running... any ideas?
it completes after 2 minutes or so
it seems mostly fixed by using
runBlockingTest
and adding a
advanceTimeBy(120000)
at the end
(and adding a
CoroutineTestRule
)
g
should have mentioned that I’m using Android / JVM 1.6, sorry
But Job works fine on Android
i
await
appeared not to exist? Then I tried
wait()
and it showed an error with JVM 1.6. What am I missing?
a
I think you need to include kotlinx.coroutines library
g
Yes, it's part of kotlinx.coroutines. But for job you need .join(), not .await(), but if you want to return value from callback you can use CompletableDeferred() + .await()