Randomize
Randomize

Reputation: 9103

How to test async Mongo query?

Is there any good strategy to test an async insert to a mongodb collection using MongoDB Scala driver 1.1:

driver.myCollection.insertOne(doc).subscribe(new Observer[Completed] {

      override def onNext(result: Completed): Unit = /* do something */

      override def onComplete(): Unit = /* do something */

      override def onError(e: Throwable): Unit = /* do something */
    })

Any mock suggested to run in it in a test? Mocking the Observable? And in case of integration test?

Upvotes: 1

Views: 412

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149548

One possible solution is to invoke insertOne and turn the Observable[T] into a Future[T] and use Await.result to synchronously block on it. This conversion is defined inside the ScalaObservable[T] implicit class:

import org.mongodb.scala.ObservableImplicits._

val future = driver
              .myCollection
              .insertOne(docs)
              .toFuture()

Await.result(future, Duration(3000, MILLISECONDS))

Note this requires the import of ObservableImplicits.

Upvotes: 1

Related Questions