【发布时间】:2021-05-05 10:43:08
【问题描述】:
我正在尝试使用 scalatestplus-play(4.0.3) 测试我的代码。我也使用 mockito-core(3.7.7)。我的测试代码不起作用。它以异常结束;
[info] java.lang.NullPointerException: Cannot invoke "scala.concurrent.Future.flatMap(scala.Function1, scala.concurrent.ExecutionContext)" because "this.future" is null
[info] at core.utils.Extensions$GetOrFail.getOrFailWith(Extensions.scala:12)
[info] at services.ShowcaseService.update(ShowcaseService.scala:42)
[info] at services.ShowcaseServiceSpec.$anonfun$new$5(ShowcaseServiceSpec.scala:59)
[info] at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
[info] at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
[info] at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
[info] at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
[info] at org.scalatest.Transformer.apply(Transformer.scala:22)
[info] at org.scalatest.Transformer.apply(Transformer.scala:20)
[info] at org.scalatest.WordSpecLike$$anon$3.apply(WordSpecLike.scala:1075)
也是我的测试代码;
val showcase = Showcase("id", "title", None, StrategyType.manuel, active = false, RecordTime())
val updatedShowcase = Showcase("id", "titleChange", Option("descChange"), StrategyType.manuel, active = false, RecordTime())
val showcaseUpdateRequest: ShowcaseUpdateRequest = ShowcaseUpdateRequest(Option("titleChange"), Option("descChange"))
val id = "id"
when(showcaseRepository.findOneById(id)).thenReturn(Future(Some(showcase)))
when(showcaseRepository.update(showcaseUpdateRequest, id)).thenReturn(Future(updatedShowcase))
val result = showcaseService.update(showcaseUpdateRequest, id)
展示服务;
def update(req: ShowcaseUpdateRequest, id: ShowcaseId): Future[Showcase] = for {
_ <- showcaseRepository.findOneById(id).getOrFailWith(ShowcaseNotFoundException(id))
updatedShowcase <- showcaseRepository.update(req, id)
} yield updatedShowcase
最后是发生错误的隐式类;
implicit class GetOrFail[T](future: Future[Option[T]]) {
def getOrFailWith[E <: Throwable](ex: E)(implicit ec: ExecutionContext): Future[T] = future flatMap {
case None => Future.failed(ex)
case Some(t) => Future.successful(t)
}
}
【问题讨论】:
-
您能否说明您在哪里创建了
GetOrFail类?看来你是用null创建的 -
@TomerShetah 我已经在描述中展示了它并隐式创建了它。
-
仍然缺少可以帮助您的详细信息。你能添加一个完整的测试吗?我们需要一个minimal reproducible example。
-
@TomerShetah 你能再检查一下吗?
标签: scala playframework mockito scalatest