我有一个带有经过身份验证的路由的播放应用程序。我实现了一个身份验证器,将用户存储到弹性搜索中。我的控制器中的安全方法使用注释进行了@Security.Authenticated
注释。对于我使用 mockito 进行的单元测试,我想模拟这个类,但我不知道该怎么做。
我将 DI 与 Guice 一起使用。所以我尝试了这种方法:
开发一个 AuthenticatorWrapper 如下:
public class AuthenticatorWrapper extends Security.Authenticator { private Authenticator authenticator; @Override public String getUsername(Http.Context ctx) { return authenticator.getUsername(ctx); } @Override public Result onUnauthorized(Http.Context ctx) { return authenticator.onUnauthorized(ctx); } @Inject public void setAuthenticator(Authenticator authenticator) { this.authenticator = authenticator; } }
这个类有一个 Authenticator 作为参数,应该在应用程序启动时由 Guice 注入。
我开发了一个定义类绑定的 guice
Authenticator.class
模块MyCustomAuthenticator.class
我的安全路线带有注释
@Security.Authenticated(AuthenticatorWrapper.class)
在我的测试中,我可以轻松地提供类MyCustomAuthenticator
的模拟,我创建模拟,定义测试范围 guice 模块,并定义从Authenticator.class
到我的模拟的绑定。
我认为这应该可行,但事实并非如此。无论是在正常运行时还是在我的测试中,绑定似乎都不起作用。我nullPointerException
从包装器中Authenticator
得到:Guice 没有注入参数。
所以我的问题是:
- Authenticator 是从 Guice 注入身份验证器的好方法吗?也许有一种更简单的方法可以将 play Authenticator 注入 Guice 的注释中?
- Guice 没有将 Authenticator 注入我的包装器中是否正常?[编辑-> 是的,因为注释手动实例化了我的对象并且不使用 guice。我对吗?]
- 我可以通过直接设置到注释中来简化我的应用程序
MyCustomAuthenticator
,但是如何在我的测试中模拟这个身份验证器?
谢谢 :)