簡體   English   中英

如何在運行 cucumber 測試時等到執行完成

[英]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()時,代碼不會停止,直到CallbackcallMethod內部完全執行並直接繼續執行@Then checkResponse()

我不確定如何停止執行以便執行Callback並使用正確的值更新result ,因為我需要在 StepDefs 內的StepDefs @Then checkResponse()中使用此result值。

這不是解決此問題的萬無一失的解決方案。 但是這個解決方案適用於我當前的用例場景。

我們可以阻止@Then方法並將其delay一段時間,比如說10s 通過這樣做,我們希望@When方法完全執行並返回responseexception

@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM