Mongodb Scala 驱动程序:如何测试错误?

Mongodb Scala Driver: How to test an error?

我正在使用 Scala 驱动程序为 Mongodb (1.1.1) 编写一种集成测试。

我有一个简单的插入查询,我可以使用 futureobserver 以这种方式管理它:

// with observer
driver.myCollection.insertOne(doc).subscribe(new Observer[Completed] {
      override def onNext(result: Completed) = /* do something */
      override def onComplete() = /* do something */
      override def onError(e: Throwable) = /* do something */
    })

// with future
val f = driver.myCollection.insertOne(doc).toFuture()
f onComplete {
      case Success(successMsg) => /* do something */
      case Failure(failureMsg) => /* do something */
    }
  }

如何在 Observer and/or Failure 中测试 onErrorFuture 中? 我怎样才能触发这种情况?

目前我正在使用Mongodb Embedded (flapdoodle)

如果我在测试开始时关闭 Mongodb,我会得到一个看起来与该错误无关的超时。

更新

我已将 WriteConcern 添加到 collection:

database.getCollection(myCollection).withWriteConcern(WriteConcern.ACKNOWLEDGED)

但这并没有改变任何东西。

futures/observers 返回的错误是否包括超时错误(当数据库或网络因某些原因关闭时引起)?

实现错误的一种方法是在集合上创建唯一索引,如下所述:https://docs.mongodb.com/manual/core/index-unique/ 创建唯一索引后,您可以插入一个项目,然后再次尝试插入它。这样你就会得到一个错误。

关于你的问题,抛出的超时是否也算在 onError 中,答案是肯定的,它很重要。 这是我的代码片段:

def findByTitle(title:String)(implicit ec:ExecutionContext):Future[Option[Document]] = {
    val collection = db.getCollection("items")
    collection.find(equal("title", title))
      .toFuture()
      .recoverWith{case e:Throwable => {println("Simulated error happened"); println(e); Future.failed(e)}}
      .map{seq => if(seq.isEmpty) None else Some(seq.head)}
  }

在 UI 上单击触发此方法调用的按钮之前,我已使用命令行命令 net stop MongoDB 停止了 MongoDB 服务(我在 Windows 上)。然后我触发了动作,一段时间后超时触发,我在我的控制台中看到了这个:

[info] p.c.s.NettyServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

Server started, use Alt+D to stop

[info] play.api.Play - Application started (Dev)
Simulated error happened
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoException: java.io.IOException: The remote computer refused the network connection.
}, caused by {java.io.IOException: The remote computer refused the network connection.
}}]
[error] application - 
....

所以你可以看到超时也被处理了,应该是因为 MongoTimeoutExceptionThrowable.