[英]How to wait until execution is completed while running cucumber tests
我正在 Android Studio 的Android項目中實施Cucumber 測試。
我的項目中有StepDefs
class,其中包含 Cucumber .features
的步驟定義。
@When("^(\\S+) is called$")
fun callFunction(methodName: String) = runBlocking {
val job = launch {
when (methodName) {
"method" -> {
testData.callMethod()
}
}
}
job.join()
}
@Then("response should contain {}")
fun checkResponse(response: String) {
try {
// logic for checking response
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: ParseException) {
e.printStackTrace()
} catch (e: JsonProcessingException) {
e.printStackTrace()
}
}
我還有一個TestData
class,它具有我調用的所有方法,它執行進行 API 調用和獲取數據的實際工作。
以下方法是TestData
class 其中result
是 class 屬性
class TestData {
result = JSONObject()
private set
fun callMethod() {
try {
val client: Client = initClient()
client.actualMethod(records, object : Callback {
override fun onFailure(exception: Any) {
Log.d("FAILURE", "$exception")
result = exception as JSONObject
}
override fun onSuccess(responseBody: Any) {
Log.i("SUCCESS", "$responseBody")
result = responseBody as JSONObject
}
})
} catch (e: Exception) {
Log.e("ERROR", e.toString())
handleError(e)
}
}
}
問題是,當調用@When callFunction()
時,代碼不會停止,直到Callback
在callMethod
內部完全執行並直接繼續執行@Then checkResponse()
。
我不確定如何停止執行以便執行Callback
並使用正確的值更新result
,因為我需要在 StepDefs 內的StepDefs
@Then checkResponse()
中使用此result
值。
這不是解決此問題的萬無一失的解決方案。 但是這個解決方案適用於我當前的用例場景。
我們可以阻止@Then
方法並將其delay
一段時間,比如說10s
。 通過這樣做,我們希望@When
方法完全執行並返回response
或exception
。
@Then("response should contain {}")
fun checkResponse(response: String) = runBlocking {
delay(10000)
try {
// logic for checking response
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: ParseException) {
e.printStackTrace()
} catch (e: JsonProcessingException) {
e.printStackTrace()
}
}
注意 - 在build.gradle
文件中添加 kotlin 協程依賴項
androidTestImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.1'
您可以檢查與您的應用程序兼容的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.