jeudi 30 juin 2016

Failing to stub somewhat complex method calls with Mockito (Scala)

Today, my colleague and myself were fighting with difficulties to stub a method of a dependency in one of out unit tests.

The service class under test looks something like this:

class MongoChecklistResultRepository @Inject()(system: ActorSystem,
                                               reactiveMongoApi: ReactiveMongoApi,
                                               checklistResultVersioningService: ChecklistResultVersioningService)
...
override def count(): Future[Int] = collection(ResultsCollectionName).count()
...

private def collection(name: String): JSONCollection =
    reactiveMongoApi.db.collection[JSONCollection](name)
    }

And inside the test that should test count method, we are trying to mock the collection object that we getting from driver and eventually stub it's count method:

doReturn(Future.successful(1)).when(jsonCollection).count()

All looks valid, but when executed, collection(ResultsCollectionName).count() always retuns null (in simple words the stub is not working.

if we look on the count method os generic collection, we'll see much more complex signature:

def count[H](selector: Option[pack.Document] = None, limit: Int = 0, skip: Int = 0, hint: Option[H] = None)(implicit h: H => CountCommand.Hint, ec: ExecutionContext): Future[Int]

And I beleive, this is the exact reason why the stubbing does not work.

We also tried doing this:

doReturn(Future.successful(1)).when(jsonCollection).count[MockCommand](None, 0, 0, None)

Also, didn't help. How can create reliable stub for these kind of methods?

Thanks,

Aucun commentaire:

Enregistrer un commentaire