Search code examples
scalascalatestscalamock

Mocking configuration objects with MockFactory


I am doing some tests, and in many cases I have a configuration of an FTP / HTTP.

I am working with Scala and the following libraries in my sbt:

"org.scalatest" %% "scalatest" % "3.0.1" % Test,
"org.scalamock" %% "scalamock" % "4.1.0" % Test,

I am doing for the following code as an example of a configuration mocked, inside of my test:

val someConfig = SomeConfig(
  endpoint = "", 
  user = "", 
  password = "", 
  companyName="", 
  proxy = ProxyConfig("", 2323)
)

But I feel it is not nice to do this for each configuration that I am going to be dealing with...

I would like to create the following:

val someConfig = mock[SomeConfig]

but when my code tries to reach the proxy property, which is a case class, it fails with a null pointer exception.

I would like to know how to mock case classes that contains other case classes and make my code a bit more clear, is there a way to do this with MockFactory?


Solution

  • You can try to mock it like this:

    val someConfig = mock[SomeConfig]
    when(someConfig.proxy).thenReturn(ProxyConfig("", 2323))
    

    So it will return ProxyConfig("", 2323) when you try to get someConfig.proxy.

    The above code is using Mockito due to a known limitation of ScalaMock