Reputation: 27849
I recently started programming in Scala. I have a project with a hierarchy of classes that call each other. Eventually, they last one calls a singleton DAL (Data Access Layer) object that calls a stored procedure in MySQL.
I have a DAL object with the following signature:
def callStoredProcedure(procName: String, params: Array[String]): Boolean
I'd like to write a test that calls a function of the top level class, and checks out what procName
was passed to the function.
How do I go about creating a mock for the DAL object? How can I inject it into the process pipeline, or is there a better/recommended way to replace the singleton with a mock that just returns the procedure name rather than calling it?
We're currently using Mockito, but I'm open to anything.
Upvotes: 0
Views: 1711
Reputation: 4320
You can do:
class Foo(dal: DAL)
val testMe = new Foo(dal = mock[DAL.type])
Cheers
Upvotes: 0
Reputation: 40508
Don't use singletons directly, that's not a good idea. You know why? Because you can't mock them for unit testing, duh. Make it a parameter to your class instead:
trait DAL {
def callStoredProcedure(procName: String, params: Array[String]): Boolean
}
object DALImpl extends DAL {
def callStoredProcedure(procName: String, params: Array[String]): Boolean = doStuff
}
class Foo(dal: DAL = DALImpl)
val testMe = new Foo(mock[DAL])
or
class Foo {
def dal: DAL = DALImpl
}
val testMe = new Foo {
override def dal = mock[DAL]
}
Upvotes: 3