3

我有一个带有经过身份验证的路由的播放应用程序。我实现了一个身份验证器,将用户存储到弹性搜索中。我的控制器中的安全方法使用注释进行了@Security.Authenticated注释。对于我使用 mockito 进行的单元测试,我想模拟这个类,但我不知道该怎么做。

我将 DI 与 Guice 一起使用。所以我尝试了这种方法:

  1. 开发一个 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 注入。

  2. 我开发了一个定义类绑定的 guiceAuthenticator.class模块MyCustomAuthenticator.class

  3. 我的安全路线带有注释@Security.Authenticated(AuthenticatorWrapper.class)

在我的测试中,我可以轻松地提供类MyCustomAuthenticator的模拟,我创建模拟,定义测试范围 guice 模块,并定义从Authenticator.class到我的模拟的绑定。

我认为这应该可行,但事实并非如此。无论是在正常运行时还是在我的测试中,绑定似乎都不起作用。我nullPointerException从包装器中Authenticator得到:Guice 没有注入参数。

所以我的问题是:

  • Authenticator 是从 Guice 注入身份验证器的好方法吗?也许有一种更简单的方法可以将 play Authenticator 注入 Guice 的注释中?
  • Guice 没有将 Authenticator 注入我的包装器中是否正常?[编辑-> 是的,因为注释手动实例化了我的对象并且不使用 guice。我对吗?]
  • 我可以通过直接设置到注释中来简化我的应用程序MyCustomAuthenticator,但是如何在我的测试中模拟这个身份验证器?

谢谢 :)

4

1 回答 1

0

A 找到了解决方法。我只是使用了 Play framework 2.4 提供的访问方法,因为它完全集成了 Guice。这是我的身份验证包装类:

public class AuthenticatorWrapper extends Security.Authenticator {

    private final Security.Authenticator authenticator;

    public AuthenticatorWrapper() {
        authenticator = Play.application().injector().instanceOf(Security.Authenticator.class);
    }

    @Override
    public String getUsername(Http.Context ctx) {
        return authenticator.getUsername(ctx);
    }

    @Override
    public Result onUnauthorized(Http.Context ctx) {
        return authenticator.onUnauthorized(ctx);
    }
}

我只是使用Play.application().injector()访问器来获取 Guice 提供的Security.Authenticator实例。所以在我的 application.conf 中,我只配置了一个 Guice 模块,它将 Security.Authenticator 绑定到想要的实现。

于 2015-03-31T12:19:14.447 回答