英文:
Testing private functions with junit and mockk in Kotlin
问题
如何在 Kotlin 中使用 JUnit 和 MockK 测试在 init 块中调用的私有函数?
示例:
class ViewModel(private val repository: Repository) : ViewModel() {
init {
doSomething()
}
private fun doSomething() = viewModelScope.launch {
// 使用 repository 做一些操作
}
}
实际上,我不想将该函数更改为公有,因为它应该仅在 init 块中执行。
英文:
How do I test a private function called in the init block using junit and mockk in Kotlin?
Example:
class viewModel(private val repository: Repository) : ViewModel() {
init {
doSomething()
}
private fun doSomething() = viewModelScope.launch {
//do something with the repository
}
}
Actually I would not like to change the function to public, because it should only be executed in the init block.
答案1
得分: 1
你通过使私有函数可访问来测试它。这真的很简单。在这种情况下,要么使用 public
要么使用 internal
都可以。您还可以添加一个注解,比如 @VisibleForTesting
,将其标记为仅测试可见,并且一些集成开发环境甚至会在您在其容器之外使用这样的函数时提供警告(例如类
英文:
You test a private function by making it accessible. It's really that simple. Either public
or internal
will do in this case. You can add an annotation like @VisibleForTesting
to mark it as test-visible only, and some IDEs will even give you a warning if you use such a function outside its container (e.g. class).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论