MaheshGupta
MaheshGupta

Reputation: 153

Unit test cases for Callbacks using Junit

I'm trying to write some unit-test cases for a class with functions that has callbacks as arguments (Please see code below)

class NetworkApi(private val url: String) {

    fun getToken(listener: (String) -> Unit) {
        Thread(Runnable {
            Thread.sleep(2000)
            if (TextUtils.isEmpty(url)) listener("")
            else listener("Dummy token")
        }).start()
    }
}

and the unit test case is

@RunWith(AndroidJUnit4::class)
class NetworkApiTest {

    var networkApi: NetworkApi? = null

    @Test
    fun testEmptyToken() {
        networkApi = NetworkApi("")
        networkApi?.getToken {
            Assert.assertThat(it, isEmptyOrNullString())
        }
    }

}

And whenever I run this test case, I do get success all the time, no matter what values I send. I know that I'm not doing exact way. Can someone please help me writing unit test cases for classes in JUnit.

Upvotes: 1

Views: 398

Answers (1)

Rene
Rene

Reputation: 6258

The problem is that the test finishes before the callback is invoked and the assert is in the wrong thread. You have to copy the result from the callback back to the main thread. Use a CompletableFuture. If you like to fail the test after a period of time you can use the get method with a timeout value:

@RunWith(AndroidJUnit4::class)
class NetworkApiTest {
    var networkApi: NetworkApi? = null

    @Test
    fun testEmptyToken() {
        val future = CompletableFuture<String>()
        networkApi = NetworkApi("")
        networkApi?.getToken {
            future.complete(it)
        }
        val result = future.get(3,TimeUnit.SECONDS)
        Assert.assertThat(it, isEmptyOrNullString())
    }
}

Upvotes: 4

Related Questions