mardi 29 mars 2016

How to mock `TResult DefaultsTo Document` in scala

I am working on a unit test for a small proxy class to scala mondo driver. One of the methods I have is getting connection by name from database object:

def collection(collectionName: String): MongoCollection[Document] = {
    logger.info("Getting collection " + collectionName)
    defaultDB.getCollection[Document](collectionName)
  }

where defaultDB is an instance of MongoDatabase class.

In my test, I want to mock the method getCollection of of MongoDatabase class, like so:

val collection = mock[MongoCollection[Document]]

val database = mock[MongoDatabase]
when(database.getCollection[Document]("collection")).thenReturn(collection)

This, of coarse, will return nothing, since the real signature looks like this:

def getCollection[TResult](collectionName: String)(implicit e: TResult DefaultsTo Document, ct: ClassTag[TResult]): MongoCollection[TResult]

So, we tried mocking the other two implicit arguments:

implicit val e = mock[Document DefaultsTo org.mongodb.scala.Document]
      implicit val classTag = mock[ClassTag[Document]]

      val collection = mock[MongoCollection[Document]]

      val database = mock[MongoDatabase]("collection")(e, _: ClassTag[Document])
      when(database.getCollection[Document]("collection")(e, classTag)).thenReturn(collection)

And now, i am getting the following error:

[error] Access to protected object DefaultHelper not permitted because [error] enclosing package mongo is not a subclass of [error] package bson in package scala where target is defined [error] import org.mongodb.scala.bson.DefaultHelper.DefaultsTo [error]
^ [error] /app/process-street/test/mongo/MongoDriverSpec.scala:61: not found: type DefaultsTo [error] implicit val e = mock[Document DefaultsTo org.mongodb.scala.Document]

And in fact, DefaultHelper is protected... Is there any way around this? What are my other options to mock getConnection method?

Thanks,

Aucun commentaire:

Enregistrer un commentaire