How to test import implicit dependencies

11 views
Skip to first unread message

Shamsh Tabrij

unread,
Apr 4, 2015, 4:49:49 AM4/4/15
to specs2...@googlegroups.com
//DataBaseAdapterObject.scala
package services.db
object DataBaseAdapterObject{
def findAllBlogItems() : List[String] = {
........
........
List("One", "Two", "Three")
}
}

//BaseService.scala
package services
import services.db._
object BaseService {
implicit val db = DataBaseAdapterObject;
}


//BlogItemService.scala
package services
import services.BaseService._

object BlogItemService {
def findAll() : List[String] = {
db.findAllBlogItems()
}
}


For above implementation I want to write unit test for the BlogItemService.findAll, The problem is because the db val is resolved by import I cannot mock the db object.
Does anybody know how to mock that implicit import db.

The code can be written differently by implementing DI but I want to know if any work around for this case?

etorreborre

unread,
Apr 4, 2015, 5:07:17 AM4/4/15
to specs2...@googlegroups.com
Can you change any of the code in BlogItemService.scala?

One option would be to rewrite the findAll function so that it delegates to findAllWithDb

  def findAll(): List[String] = 
    findAllWithDb(db)

  def findAllWithDb: DabaseAdapterObject => List[String] = 
     // your implementation
  
Then you can unit test findAllWithDb.

This also moves you toward using a Reader pattern where you can sequence methods like findAllWithDb with a for comprehension as you evolve your application.

Eric.

Shamsh Tabrij

unread,
Apr 4, 2015, 8:18:03 AM4/4/15
to specs2...@googlegroups.com
Thanks for the reply, Definitely this can be solution but needs more code. I was wondering if there is any way to override the context of db when writing the specification?

etorreborre

unread,
Apr 4, 2015, 7:19:30 PM4/4/15
to specs2...@googlegroups.com
Sorry I don't know any way that would be absolutely non-invasive with the code you have.

But I can only encourage you to either use a Reader pattern or to use a DI framework and refactor your code. This has really made my life a lot easier for testing specs2 3.x compared to 2.x.

Eric.

Shamsh Tabrij

unread,
Apr 6, 2015, 1:43:18 AM4/6/15
to specs2...@googlegroups.com
Thanks Eric, I also think the code should be refactored.
Reply all
Reply to author
Forward
0 new messages