单元测试总是returns scala match error null or null pointer exception

Unit test always returns scala match error null or null pointer exception

目前正在尝试使用 specs2 和 scalatest 测试身份验证控制器,我的应用程序运行良好,但测试总是 return NullPointerException 或 Scala 匹配错误 null

  val userRepository: UserRepository = mock[UserRepository]
  val userService: UserService = mock[UserService]
  val authenticator: Authenticator = mock[Authenticator]
  val authenticationService: AuthenticationService = mock[AuthenticationService]
  implicit val ec = mock[ExecutionContext]
  implicit val materializer = mock[Materializer]
  val authenticationController = new AuthenticationController(Helpers.stubControllerComponents(
    playBodyParsers = Helpers.stubPlayBodyParsers(materializer)
  ), authenticationService, authenticator, userService)

    "User" should "login successfully" in {
      val request = FakeRequest(POST, "/api/login").withHeaders(CONTENT_TYPE -> "application/json")
        .withBody[JsValue](Json.parse("""{"email": "nghia_hd@flinters.vn", "password": "a12306789H@"}"""))
      val result: Future[Result] = authenticationController.login().apply(request)
      result.map {data => data.header.status shouldBe OK}
    }
}

使用Intellij debugger时,好像是这里出现了异常,但是我不太明白怎么解决

  def login: Action[JsValue] = Action(parse.json) {
    implicit request =>
      UserLoginForm.form.bindFromRequest.fold(
        formWithErrors => badRequestWarning(formWithErrors.errors),
        user => {
-->       authenticationService.verify(user) match {
            case Success(result) => success(UserPayload.encode(result))
            case Failure(exception) => exception match {
              case _: PasswordNotMatch => error(Unauthorized, 401, "Password not match")
              case _: EntityNotFoundException =>  error(Unauthorized, 400, "Email not found")
              case _ => error(InternalServerError, 500, "An error occurred")
            }
          }
        }
      )
  }

我没有具体使用 specs2/scalatest,但通常您需要指定模拟方法的响应。您需要将此添加到测试中:

when(authenticationService.verify(any())).thenReturn(someMockUser)

否则(取决于您的测试设置)它将 return 为空。还有测试框架,如果在模拟对象上调用未模拟的方法,您可以抛出异常。