简体   繁体   中英

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.

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())
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM