简体   繁体   English

如果协程中存在“by injection{parametersOf(”someValue“)}”,则协程的单元测试失败

[英]Unit test fails for coroutine if “by inject{parametersOf(”someValue“)}” is present within coroutine

I have a coroutine in my viewModel which runs perfectly fine.我的 viewModel 中有一个协程,它运行得非常好。 When I try to unit test the same, it throws the following error " Could not create instance for [type:Factory,primary_type:..MyService "当我尝试对其进行单元测试时,它会引发以下错误“ Could not create instance for [type:Factory,primary_type:..MyService

I am injecting a service and making an API call which works fine while unit testing.我正在注入服务并进行 API 调用,该调用在单元测试时工作正常。 If the API fails, I am retrying the same API call with a new instance of Service with different parameters.如果 API 失败,我将使用具有不同参数的新服务实例重试相同的 API 调用。 This works fine in my application but fails in unit test.这在我的应用程序中运行良好,但在单元测试中失败。 Here is the following code:这是以下代码:

coroutineScope.launch {
        try {
            var getResponse = myApi?.getCodeApi()
            if (getResponse?.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                // Retrying with instance of service with a different token
                val newMyApiService: MyService? by inject { parametersOf(newToken) }
                getResponse = newMyApiService?.getCodeApi()

            }
            checkResponse(getResponse)
        } catch (exception: Exception) {
            Timber.e(exception)
        }
    }

Is there a way to fix this?.有没有办法来解决这个问题?。 I have taken all the required measures like startingKoinApp for the test environment, also included the required Koin modules before starting to test.我已经采取了所有必要的措施,比如测试环境的startingKoinApp,在开始测试之前还包括了所需的Koin模块。

A part of unit test looks something like this单元测试的一部分看起来像这样

 whenever(myAPi.getCodeApi()).thenReturn(properResponse)
        val errorResponse : Response<DataModel> = mock()
        whenever(response.code()).thenReturn(HttpsURLConnection.HTTP_UNAUTHORIZED)
        whenever(myAPi.getCodeApi()).thenReturn(errorResponse)

This can be fixed by replacing the line这可以通过更换线路来解决

val newMyApiService: MyService? by inject { parametersOf(newToken) }

with

val newMyApiService: getNewService(newToken)

The new method will be新方法将是

fun getNewService(newToken: String): MyService? {
  return MyService? by inject { parametersOf(newToken) }
}

Now within your unit test, you can mock the method using power mockito现在在您的单元测试中,您可以使用 power mockito 模拟该方法

val underTestsSpy = PowerMockito.spy(underTests)
        PowerMockito.doReturn(myserviceApi).`when`(underTestsSpy, 
 "getNewService", newToken)

Through this, you can mock a new service instance that is created within the method being tested通过这个,您可以模拟在正在测试的方法中创建的新服务实例

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

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