scalatest-使用fallbackto测试未来的方法

klr1opcd  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(331)

前提:当我的api响应用户对象的请求时,我想尝试用 case class PartnerView(id: String, vipStatus: Option[Boolean], latestSession: Option[Timestamp] . 由于数据库有时不可靠,我使用 fallbackTo 提供可选的值,从而不在用户json响应中显示它们。
到目前为止,下面的实现似乎还可以工作(通过postman运行请求返回用户json,但没有可选值),但是我的单元测试会抱怨,好像我有一个未捕获的异常。
服务级别:

  1. class Service(repo: Repository) {
  2. def get(id: String): Future[Partner] = {
  3. val account = repo.getAccount(id)
  4. val getLatestSession = repo.getLatestSession(id)
  5. val partnerView = (for {
  6. account <- getAccount
  7. latestStartTime <- getLatestSession.map {
  8. case Some(x) => x.scheduledStartTime
  9. case _ => None
  10. }
  11. } yield PartnerView(partnerId, account.vipStatus, latestStartTime))
  12. .fallbackTo(Future.successful(PartnerView(id, None, None)))
  13. partnerView
  14. }
  15. }

存储库类:

  1. class Repository(database: DatabaseDef, logger: LoggingAdapter) {
  2. def getAccount(id: String): Future[Account] = database.run((...).result.head)
  3. .recover {
  4. case e: Exception =>
  5. logger.error(e, "DB Server went down")
  6. throw e
  7. }
  8. def getLatestSession(id: String): Future[Option[Session]] = database.run((...).result.headOption)
  9. .recover {
  10. case e: Exception =>
  11. logger.error(e, "DB Server went down")
  12. throw e
  13. }
  14. }

单元测试:

  1. class ServiceSpec extends AsyncFlatSpec with AsyncMockFactory with OneInstancePerTest {
  2. val mockRepo = mock[Repository]
  3. val service = new Service(mockRepo)
  4. behaviour of "Service"
  5. it should "get an empty PartnerView when the repository get an Exception" in {
  6. (mockRepository.getAccount _)
  7. .expects("partner")
  8. .throwing(new Exception)
  9. service.get("partner")
  10. .map(partnerView => assert(partnerView.id == "partner" && partnerView.vipStatus.isEmpty))
  11. }
  12. }

测试将失败并显示消息

  1. Testing started at 5:15 p.m. ...
  2. java.lang.Exception was thrown.
  3. {stacktrace here}

我在等你 Exception

ttygqcqt

ttygqcqt1#

通过将模拟设置更改为以下设置,测试成功运行:

  1. it should "get an empty PartnerView when the repository get an Exception" in {
  2. (mockRepository.getAccount _)
  3. .expects("partner")
  4. .returning(Future.failed(new Exception))
  5. ...
  6. }

自从 recover 方法 Package Exception 内部 Future 资料来源:
recover与recoverwith
scala官方文章

相关问题