我正在尝试模拟我与外部API的交互,该外部API检查令牌以查看用户是否有权执行某些操作(它当前是一个单独的API作为PoC,稍后将被移动到中间件中)
相关信息(SBT DSL)
"org.specs2" %% "specs2-core" % "4.2.0" % Test,
"org.specs2" %% "specs2-mock" % "4.2.0" % Test
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"))
}
}
}
CODE
代码使用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框架(我应该使用Spring作为我的lambda)来注入Interactions并使用DI框架进行模拟。答案 0 :(得分:0)
您需要将模拟对象传递给MyHandler
class MyHandler(interactions: Interactions) with Utils
然后
val interactions = mock[Interactions]
val myHandler = MyHandler(interactions)
MyHandler.handler(reqHandler, null)