0

给定以下代码片段

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

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

如何模拟内部单例对象hostport字段Http

4

1 回答 1

2

mockito-scala提供ReturnsDeepStubs通过IdiomaticMockito

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)
于 2018-02-03T01:12:45.137 回答