Dropwizard 0.8.0中经过身份验证的资源的单元测试

时间:2015-02-15 19:53:51

标签: java unit-testing authentication jersey-2.0 dropwizard

我想在Dropwizard 0.8.0-rc2应用程序中测试我的Jersey资源。另一个障碍是我使用TestNG而不是JUnit,所以我必须手工做一些我从DropwizardClientRule复制的东西。

现在我有一些由@Auth保护的资源。在Dropwizard 0.7.1中,我将验证器添加到测试应用程序中,如下所示:

DropwizardResourceConfig resourceConfig = DropwizardResourceConfig.forTesting(…);        
Authenticator<BasicCredentials, Identity> authenticator =
        credentials -> getAuthorizedIdentity();
resourceConfig.getSingletons().add(
        new BasicAuthProvider<>(authenticator, "TEST"));

在这里,getAuthorizedIdentity()会获取一些测试授权。这将传递给@Auth带注释的注入参数。当然,现在,随着泽西2队的事情发生了一些变化。我试过了:

DropwizardResourceConfig resourceConfig = DropwizardResourceConfig.forTesting(…);
Authenticator<BasicCredentials, Identity> authenticator =
        credentials -> getAuthorizedIdentity();
resourceConfig.register(AuthFactory.binder(
        new BasicAuthFactory<>(authenticator, "TEST", Identity.class)));

效果是我获得了所有安全资源的401。调试显示我的身份验证函数永远不会被调用!如果我删除了注册,那么我将不再获得401s(因此注册不会没有效果),但现在安全资源是不安全的,并获得null注释参数的@Auth

那么,如何将验证器添加到测试上下文中以便它可以工作?生产代码几乎在同一行上正常工作。

2 个答案:

答案 0 :(得分:1)

这个问题最近已修复。

请参阅https://github.com/dropwizard/dropwizard/pull/966

答案 1 :(得分:0)

我遇到了同样的问题,在看了dropwizard-auth项目中的测试之后,我来到这个解决方案,希望它有所帮助。

public class ExamplesResourceTest extends JerseyTest
{
    @Override
    protected TestContainerFactory getTestContainerFactory()
        throws TestContainerException {
        return new GrizzlyWebTestContainerFactory();
    }

    @Override
    protected DeploymentContext configureDeployment() {
        return ServletDeploymentContext.builder(new ExampleTestResourceConfig())
            .initParam( ServletProperties.JAXRS_APPLICATION_CLASS, ExampleTestResourceConfig.class.getName() )
            .initParam( ServerProperties.PROVIDER_CLASSNAMES, ExampleResource.class.getName() )
            .build();
    }


    public static class ExampleTestResourceConfig extends DropwizardResourceConfig {

        private ObjectMapper mapper = Jackson.newObjectMapper();
        private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

        public ExampleTestResourceConfig() {
            super(true, new MetricRegistry());
            register( new JacksonMessageBodyProvider( mapper, validator ) );
            register( AuthFactory.binder( new BasicAuthFactory<>( new ExampleAuthenticator(), "realm", String.class ) ) );
        }
    }

    @Test
    public void exampleTest() throws AuthenticationException
    {
        Response response = target( "/api/example" )
            .request( MediaType.APPLICATION_JSON )
            .header( HttpHeaders.AUTHORIZATION, "Basic QmlsYm86VGhlU2hpcmU=" )
            .get();

        assertThat( response.getStatus() ).isEqualTo( 200 );
    }
}