gpt4 book ai didi

swift - Kotlin 等价于 Swift 期望/ promise

转载 作者:可可西里 更新时间:2023-11-01 01:56:09 25 4
gpt4 key购买 nike

我正在尝试为我的 native 移动应用程序编写一些单元测试,但在我的 Android 测试中遇到了障碍。具体来说,我正在努力寻找 Kotlin 版 Swift 的期望/ promise 的示例。

我找到了 Kotlin Promises 的例子,但它们似乎比需要的要复杂得多......

例如在我的iOS项目中测试login API函数:

func testLogin() {

/// Prepare for login
if CURRENT_USER != nil {
logout()
}

/// Login
let promise = expectation(description: "User is logged in.")

// 1. Given
var isSuccess: Bool = false

// 2. When
User.login(username: maleUsername, password: malePassword, success: {
isSuccess = true
promise.fulfill()
}) { (_, agreeToTerms) in
XCTFail()
}
wait(for: [promise], timeout: maxTimeOut)

// 3. Then
XCTAssertNotNil(CURRENT_USER)
XCTAssertTrue(isSuccess)

/// Logout
logout()
}

这对我来说很简单。我有一个异步方法 login,它有两个可能的完成 block :successfailure;在评估之前,我需要等待其中一个完成。为此,我在调用之前创建了一个promise,然后在两个完成 block 中fulfill该promise,然后我等待该promise在运行我的断言之前完成。

现在在 Kotlin 中,我有一个类似的测试:

private val loginFragment = LoginFragment()

@Test
fun loginTest() {

val username = ""
val password = ""

// TODO: Create Promise

loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer {
loginFragment.activity?.onResult(it?.result,

onSuccess = {
// TODO: Fill Promise
},
onValidationError = {
// TODO: Fail Test
})
})

// TODO: Assertions

}

但我找不到与 swift 的 promises 等价的..

Kotlin 中有吗?如果没有,我将如何在 Kotlin 中实现我的 Swift 的 testLogin 方法的一个版本?

最佳答案

您可以使用 Kotlin 协程,例如:

@Test
fun loginTest() {
val result = runBlocking {
val loginResult = login()
loginResult
}
if (result == "Success") {
// do your work when Success
} else {
// do your work when Error
}
}
suspend fun login(): String = suspendCoroutine { continuation ->
val username = ""
val password = ""
loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer {
loginFragment.activity?.onResult(it?.result,

onSuccess = {
continuation.resume("Success")
},
onValidationError = {
continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

})
})
}

要使用协程,您需要将下一行添加到应用程序的 build.gradle 文件依赖项中:

final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"

希望对您有所帮助。

关于swift - Kotlin 等价于 Swift 期望/ promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53291051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com