0

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.

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159

2 Answers2

3

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]
}
Dima
  • 39,570
  • 6
  • 44
  • 70
0

You can do:

class Foo(dal: DAL)

val testMe = new Foo(dal = mock[DAL.type])

Cheers

Joan
  • 4,079
  • 2
  • 28
  • 37
  • How does that help, if I may ask? I want to grab the stored proc's name, without it being actually called. Spying won't do that. Mocking would still require an injection through all layers. Correct me if I'm wrong? – Traveling Tech Guy Apr 05 '16 at 01:06
  • Yes indeed `mock[DAL.type]` will require injection just like Dima showed you but without having to bother with a trait. `spy(DAL)` is actually not relevant for you as it will actually compute the function. I edit my answer. – Joan Apr 05 '16 at 13:01