Testing private functions with junit and mockk in Kotlin

huangapple go评论66阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月29日 23:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定