2

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?

juan garcia
  • 1,326
  • 2
  • 23
  • 56

2 Answers2

2

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

juan garcia
  • 1,326
  • 2
  • 23
  • 56
earlymorningtea
  • 508
  • 1
  • 9
  • 20
  • would you provide your configuration of sbt / or any other to know which packages should I have for that syntax?, also which extentions you use in the particular test case would be great. I only see this working for getters of a certain private property, but not for public properties of a case class nested with another case class... may be something like scala faker could be a solution, but I expected this to be solved by mock factory.... – juan garcia May 22 '18 at 11:13
  • The above syntax is from Mockito. – Mario Galic May 27 '18 at 00:31
1

Parameters of case classes are translated into val fields, and ScalaMock has a known limitation where it is not able to mock val, so I think it is not possible to directly do this with ScalaMock.

Mockito does have this capability.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98