简体   繁体   English

使用Junit进行回调的单元测试用例

[英]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. 有人可以帮我为JUnit中的类编写单元测试用例。

The problem is that the test finishes before the callback is invoked and the assert is in the wrong thread. 问题在于,测试在调用回调和assert位于错误线程之前完成。 You have to copy the result from the callback back to the main thread. 您必须将结果从回调复制回主线程。 Use a CompletableFuture . 使用CompletableFuture If you like to fail the test after a period of time you can use the get method with a timeout value: 如果您希望在一段时间后无法通过测试,可以使用带有超时值的get方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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