使用scalatest测试reactivemongo会引发异常

时间:2015-12-27 14:01:20

标签: scala reactivemongo

我正在尝试在应用中测试一些功能。我有其他测试(使用反应堆的反应堆)并且正在工作,但有了这个我得到这个例外

  

[info] - 应该坚持并找到一个令牌 * FAILED *   [info]将来会返回类型异常:reactivemongo.api.commands.bson.DefaultBSONCommandError,消息:CommandError [code = 26,errmsg = ns not found,doc:{   [info] ok:BSONDouble(0.0),   [info] errmsg:“找不到ns”,   [info]代码:BSONInteger(26)   [info]}]。 (DaosApplicationSpecOneAppPerTest.scala:74)

这是测试的代码(两者都抛出相同的错误)

class UserTokenDaoMongoSpec extends DaosApplicationSpecOneAppPerTest {
  "UserTokenDao" should {
    "Persist and find a token" in withUserTokenDao { userTokenDao =>
      val future = for {
        _ <- userTokenDao.save(token)
        maybeToken <- userTokenDao.find(token.id)
      } yield {
        maybeToken.map(_ == token)
      }
      whenReady (future) { result =>
        result.get must be (true)
      }
    }

    "Remove a token" in withUserTokenDao { userTokenDao =>
      val future = for {
        _ <- userTokenDao.save(token)
        _ <- userTokenDao.remove(token.id)
        maybeToken <- userTokenDao.find(token.id)
      } yield {
        maybeToken
      }
      whenReady (future) { result =>
        result must be (None)
      }
    }
  }
}

为了简洁起见,这是继承

的方法
def withUserTokenDao[T](t: UserTokenDao => T):T = running(app) {
  val userTokenDao = new UserTokenDaoMongo
  whenReady (userTokenDao.tokens.drop()) { result =>
    t(userTokenDao)
  }
}

UserTokenDao实现

class UserTokenDaoMongo extends UserTokenDao {

  lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
  val tokens = reactiveMongoApi.db.collection[JSONCollection]("tokens")

  def find(id:UUID):Future[Option[UserToken]] =
      tokens.find(Json.obj("id" -> id)).one[UserToken]

  def save(token:UserToken):Future[UserToken] = for {
    _ <- tokens.insert(token)
  } yield token

  def remove(id:UUID):Future[Unit] = for {
    _ <- tokens.remove(Json.obj("id" -> id))
  } yield ()

}

这是UserToken的模型

class UserTokenDaoMongo extends UserTokenDao {

  lazy val reactiveMongoApi = current.injector.instanceOf[ReactiveMongoApi]
  val tokens = reactiveMongoApi.db.collection[JSONCollection]("tokens")

  def find(id:UUID):Future[Option[UserToken]] =
      tokens.find(Json.obj("id" -> id)).one[UserToken]

  def save(token:UserToken):Future[UserToken] = for {
    _ <- tokens.insert(token)
  } yield token

  def remove(id:UUID):Future[Unit] = for {
    _ <- tokens.remove(Json.obj("id" -> id))
  } yield ()

}

我不确定导致错误的原因

谢谢

1 个答案:

答案 0 :(得分:0)

原来,问题是集合令牌不存在。我进入了mongo控制台,然后创建了集合,测试开始工作。