如何模拟内部单例对象的字段?

How to mock fields of inner singleton objects?

给定以下代码片段

class Config {
  private val conf = ConfigFactory.load()

  object Http {
    val host = conf.getString("http.host")
    val port = conf.getInt("http.port")
  }
}

如何模拟内部单例对象 Httphostport 字段?

mockito-scala 通过 IdiomaticMockito

提供 ReturnsDeepStubs
import org.mockito.stubbing.ReturnsDeepStubs
import org.mockito.{ArgumentMatchersSugar, IdiomaticMockito}

val config = mock[Config](ReturnsDeepStubs)
config.Http.host returns "www.example.com"
config.Http.port returns 80

没有深度存根我们可以做到

import org.scalatest.mockito.MockitoSugar
import org.mockito.Mockito.when    

val config = mock[Config]
val httpConfig = mock[config.Http.type]
when(httpConfig.host).thenReturn("www.example.com")
when(httpConfig.port).thenReturn(80)
when(config.Http).thenReturn(httpConfig)