我有一个signout
方法,它调用另一个类的discard
方法。我想测试一下,signout
被调用时,discard
被调用一次。我试图在spy
上AuthenticatorService
,然后检查其discard
方法是否被调用,但出现错误
Wanted but not invoked:
fakeJWTAuthenticatorService.discard(
<any>,
<any>,
<any>
);
测试方法是
def signOutUser = silhouette.SecuredAction.async { implicit request =>
silhouette.env.authenticatorService.discard(request.authenticator, Ok(Json.toJson(JsonResultSuccess(messagesApi("success.signoutSuccessful")(langs.availables(0)))))) //I want to test that `discard` is called once
}
我写的测试用例是
"signOutUser" should {
"should be called when signout request is received" in {
val testEnv = new TestEnv(components = components)
val request = FakeRequest("POST", "ws/users/user-signout").withAuthenticator(testEnv.loginInfo)(testEnv.fakeEnv)
//spying calls the real method.
val authenticatorServiceSpy = Mockito.spy(testEnv.fakeSilhouette.env.authenticatorService)
val response = testEnv.controller.signOutUser(request)
val responseBody = contentAsJson(response)
println(s"response is ${responseBody}")
val result = (responseBody \ "result").get.as[String]
val message = (responseBody \ "additional-info").get.as[String]
result mustBe "success"
verify(authenticatorServiceSpy,times(1)).discard(ArgumentMatchers.any[JWTAuthenticator],ArgumentMatchers.any())(ArgumentMatchers.any())
}
}
答案 0 :(得分:0)
您可以将testEnv.fakeSilhouette.env.authenticatorService返回的对象本身设为模拟吗?那将是处理此问题的理想方法。如果要测试A类,则希望使用模拟消除对其他类(例如B类)的依赖关系,以便可以将测试仅集中在A的代码上。在这种情况下,您正在测试注销方法,它似乎取决于身份验证器服务。您是否可以注入此依赖关系,以便签出方法使用的身份验证器服务是模拟的而不是间谍的?