如何使用 guice 注入在 play 框架中模拟 Authenticator?

How to mock an Authenticator in play framework with guice injections?

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

我在 Guice 中使用 DI。所以我尝试了这种方法:

  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;
        }
    }
    

    这个 class 有一个 Authenticator 作为参数,它应该在应用程序启动时由 Guice 注入。

  2. 我开发了一个 guice 模块,定义了 class Authenticator.classMyCustomAuthenticator.class

  3. 的绑定
  4. 我的安全路由用 @Security.Authenticated(AuthenticatorWrapper.class)

  5. 注释

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

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

所以我的问题是:

谢谢:)

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

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() 访问器来获取 Security.Authenticator 实例由 Guice 提供。所以在我的 application.conf 中,我只是配置了一个 Guice 模块,它将 Security.Authenticator 绑定到想要的实现。