How to mock fields of inner singleton objects?

1k Views Asked by At

Given the following code snippet

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

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

how can host and port fields of inner singleton object Http be mocked?

1

There are 1 best solutions below

0
On BEST ANSWER

mockito-scala provides ReturnsDeepStubs via 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

Without deep stubbing we could do

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)