【问题标题】:FilesDir on mocked context Is null模拟上下文上的 FilesDir 为空
【发布时间】:2019-11-22 15:13:58
【问题描述】:

我是单元测试的新手,目前在我的 Kotlin android 应用程序中使用 Mockito。

我在我的视图模型类中使用 Koin 进行依赖注入。我已经成功地模拟了依赖项。我将 mockedContext 传递给我的 viewModel 类,但是在调用 mockedContext.filesDir 时它返回 null。

我错过了什么吗?

HomeViewModel类

init {
    directoryManager.createDirectory()
}

目录管理器

class DirectoryManager(val context:Context){

    fun createDirectory(){
        val filePath: String = context.filesDir.absolutePath
    }
}

HomeViewModelTest

@Mock
private lateinit var mockedContext: Context
private lateinit var homeViewModel: HomeViewModel

@Before
fun setup() {
    homeViewModel = HomeViewModel(mockedContext)
}

在 DirectoryManager 中为 context.filesDir 获取 null

【问题讨论】:

  • 看起来您没有为 Context 的模拟定义任何行为。
  • 如果你不想模拟上下文。搜索RobolectricInstrumented test

标签: android unit-testing kotlin mockito androidx


【解决方案1】:

我的解决方案是改用 mockedApplication!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 2017-04-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 2020-10-23
    • 2014-11-21
    • 2019-07-10
    相关资源
    最近更新 更多