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

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

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

class Service(repo: Repository) {
  def get(id: String): Future[Partner] = {
    val account = repo.getAccount(id)
    val getLatestSession = repo.getLatestSession(id)

    val partnerView = (for {
      account <- getAccount
      latestStartTime <- getLatestSession.map {
        case Some(x) => x.scheduledStartTime
        case _ => None
      }
    } yield PartnerView(partnerId, account.vipStatus, latestStartTime))
      .fallbackTo(Future.successful(PartnerView(id, None, None)))

    partnerView
  }
}

存储库类:

class Repository(database: DatabaseDef, logger: LoggingAdapter) {
  def getAccount(id: String): Future[Account] = database.run((...).result.head)
    .recover {
      case e: Exception =>
        logger.error(e, "DB Server went down")
        throw e
    }

  def getLatestSession(id: String): Future[Option[Session]] = database.run((...).result.headOption)
    .recover {
      case e: Exception =>
        logger.error(e, "DB Server went down")
        throw e
    }
}

单元测试:

class ServiceSpec extends AsyncFlatSpec with AsyncMockFactory with OneInstancePerTest {
  val mockRepo = mock[Repository]
  val service = new Service(mockRepo)

  behaviour of "Service"

  it should "get an empty PartnerView when the repository get an Exception" in {
    (mockRepository.getAccount _)
      .expects("partner")
      .throwing(new Exception)

    service.get("partner")
      .map(partnerView => assert(partnerView.id == "partner" && partnerView.vipStatus.isEmpty))
  }
}

测试将失败并显示消息

Testing started at 5:15 p.m. ...

java.lang.Exception was thrown.
{stacktrace here}

我在等你 Exception

ttygqcqt

ttygqcqt1#

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

it should "get an empty PartnerView when the repository get an Exception" in {
    (mockRepository.getAccount _)
      .expects("partner")
      .returning(Future.failed(new Exception))

    ...
  }

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

相关问题