如何模拟lifecycleScope进行单元测试?

问题描述 投票:0回答:1

我正在为我的生命周期范围编写单元测试,但在执行测试时遇到问题。

有人可以告诉我如何适当地模拟生命周期作用域吗?

示例代码:

class TestFragment : Fragment() {
  fun test() {
      lifecycleScope.launch(Dispatchers.IO) {
           val a = test2()
      }

  }

  suspend fun test2(): Boolean = true

}

有人可以告诉我如何适当地模拟生命周期作用域吗? 谢谢!!!

android kotlin unit-testing android-lifecycle
1个回答
0
投票

在幕后,

lifecycleScope
实际上访问
lifecycle
。所以只有
lifecycle
需要被嘲笑。

public val LifecycleOwner.lifecycleScope: LifecycleCoroutineScope
    get() = lifecycle.coroutineScope

为此,我创建了

LifecycleOwnerRule

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import org.junit.Rule
import org.junit.rules.TestWatcher
import org.junit.runner.Description

/**
 * A [Rule] that creates a [LifecycleOwner] with a [LifecycleRegistry] that can be used in tests.
 * The lifecycle is initially in the [Lifecycle.State.CREATED] state and is set to [Lifecycle.State.DESTROYED] when the test finishes.
 * You can use [lifecycleRegistry]'s [LifecycleRegistry.currentState] setter to change the state of the lifecycle.
 */
class LifecycleOwnerRule : TestWatcher() {

    val lifecycleOwner: LifecycleOwner = object : LifecycleOwner {
        override val lifecycle: Lifecycle get() = lifecycleRegistry
    }

    val lifecycleRegistry by lazy { LifecycleRegistry(lifecycleOwner) }

    override fun starting(description: Description?) {
        lifecycleRegistry.currentState = Lifecycle.State.CREATED
    }

    override fun finished(description: Description?) {
        lifecycleRegistry.currentState = Lifecycle.State.DESTROYED
    }
}

然后我嘲笑了

lifecycle

doReturn(lifecycleOwnerRule.lifecycleOwner.lifecycle).whenever(mockActivity).lifecycle
© www.soinside.com 2019 - 2024. All rights reserved.