1

我正在使用 play framework 2.5 和带有 scala 2.11 的剪影库。并使用 play specs2 和 mockito 编写测试代码。现在,我一直在尝试模拟抛出异常。但是,模拟总是在调用之前抛出 NullPointerException。

这是测试代码的目标。

class TestController @Inject() (
  ...
  silhouette: Silhouette[DefaultEnv]) extends Controller {

  def target() = silhouette.SecuredAction.async { implicit request =>
    try {
      silhouette.env.authenticatorService.discard(request.authenticator, Ok)
    } catch {
      case t: Throwable =>
        Future.successful(InternalServerError(...))
    }
  }
}

测试代码如下。

class TestControllerSpec extends PlaySpecification with Mockito {
  ...
  trait Context extends Scope {
    val mockTest = mock[Silhouette[DefaultEnv]]

    // This always throws a NullPointerException.
    mockTest.env.authenticatorService.discard(any[JWTAuthenticator], any[Result])(any[RequestHeader]) throws new AuthenticatorDiscardingException("AuthenticatorDiscardingException")

    lazy val appMock = new GuiceApplicationBuilder()
      .overrides(new FakeModule)
      .overrides(bind[Silhouette[DefaultEnv]].toInstance(mockTest))
      .build
  }
  ...
}

我收到如下错误消息。

[error]      java.lang.NullPointerException: null (TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$Context$1$$anonfun$40.apply(TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$Context$1$$anonfun$40.apply(TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$Context$1$class.$init$(TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$$anonfun$apply$16$$anonfun$apply$18$$anon$32.<init>(TestControllerSpec.scala:393)
[error] controllers.TestControllerSpec$$anonfun$29$$anonfun$apply$16$$anonfun$apply$18.apply(TestControllerSpec.scala:393)
[error] controllers.TestControllerSpec$$anonfun$29$$anonfun$apply$16$$anonfun$apply$18.apply(TestControllerSpec.scala:393)
4

0 回答 0