簡體   English   中英

scala特征中的specs2模擬方法從未驗證

[英]specs2 mock methods in a scala trait never verified

我正在嘗試模擬與外部API的交互,該API檢查令牌以查看用戶是否有權執行某些操作(當前是一個單獨的API,作為PoC,稍后將移入中間件)

依賴關系(SBT DSL)

"org.specs2" %% "specs2-core" % "4.2.0" % Test,
"org.specs2" %% "specs2-mock" % "4.2.0" % Test

測試

class MyHandlerSpec extends Specification with Mockito {
   def is = s2"""
     The first step is to check if the lambda is called on behalf of an 
     authenticated user. This is done by verifying that user token provided 
     as the Authorization header is valid by calling the auth API.

     Here, we can ${ConfirmThat().authLambdaWasCalled} by the handler
   """

 case class ConfirmThat() {
   def interactions = mock[Interactions]

  def authLambdaWasCalled = {
    val reqHandler = Request[Input](
       headers = Map[String, String](
          "Authorization" -> "Bearer gagagaga"
       )
      // millions of values that are not directly related
    )
    MyHandler.handler(reqHandler, null)
    there was one(interactions).authenticateUser(Some("gagagaga"))
  }
 }
}

該代碼使用MyHandler類擴展了Interactions特性:

 trait Interactions extends MyServiceTrait with AuthServiceTrait {
    def authenticateUser(token: Option[String]): Future[Either[Errors, Boolean]] = {
  Future.successful(Right(true))
 }
}

class MyHandler extends Interactions with Utils {

  override def handler(request: Request[Input], c: Context): Response[Errors, Output] = { 
    //  get the auth token from the headers as an option, 
    //  there is a method in Utils that I unit tested
    //  it been omitted here for clarity

    val authFuture = authenticateUser(bearerToken)
  }  
}

錯誤

運行代碼時,我看到以下錯誤:

The mock was not called as expected: 
[error]  Wanted but not invoked:
[error]  interactions.authenticateUser(
[error]      Some(gagagaga)
[error]  );
[error]  -> at com.lendi.lambda.MyHandlerSpec$ConfirmThat.$anonfun$authLambdaWasCalled$1(MyHandlerSpec.scala:71)
[error]  Actually, there were zero interactions with this mock. (MyHandlerSpec.scala:71)

我如何確保自己可以:

a)將身份驗證代碼移到MyHandler中,並使用specs2提供的Mockito對MyHandler進行部分模擬

b)確保我模擬了交互並將交互注入到代碼中,以便處理程序可以正確模擬它。

c)使用DI框架(我應該在自己的lambda中使用Spring)注入交互並使用DI框架對其進行模擬。

您需要將模擬對象傳遞給MyHandler

class MyHandler(interactions: Interactions) with Utils

接着

val interactions = mock[Interactions]
val myHandler = MyHandler(interactions)

MyHandler.handler(reqHandler, null)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM