【问题标题】:@Context object not injected when unit testing resteasy单元测试resteasy时未注入@Context对象
【发布时间】:2015-03-09 09:14:33
【问题描述】:

我正在尝试注册一个 @Provider,它将 Locale 对象注入到 @Context 中,以便我可以在我的 REST 资源中重用它。

按照http://bill.burkecentral.com/2011/03/09/adding-objects-that-are-context-injectable/ 的文章,我设法让提供程序运行

@Provider
public class LocaleProvider implements ContainerRequestFilter {

    public static final String DEFAULT_LANGUAGE_CODE_VALUE = "en-US";

    @Context
    Dispatcher dispatcher;

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        List<Locale> acceptableLanguages = containerRequestContext.getAcceptableLanguages();
        if (acceptableLanguages == null || acceptableLanguages.isEmpty()) {
(A)         dispatcher.getDefaultContextObjects().put(Locale.class, new Locale(DEFAULT_LANGUAGE_CODE_VALUE));
            return;
        }

        dispatcher.getDefaultContextObjects().put(Locale.class, acceptableLanguages.get(0));
    }


}

并像这样使用它

@Path("/")
public class Resource {

    @GET
    public String get(@Context Locale locale) {
        if (locale == null) {
            return "null";
        }

        return locale.getLanguage();
    }
}

到目前为止,代码在部署到 Tomcat 时效果很好。但是我在尝试对其进行单元测试时遇到了一个问题。我有

public class LocaleProviderTest {
    private Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();

    {
        dispatcher.getRegistry().addResourceFactory(new POJOResourceFactory(Resource.class));
    }

    @Test
    public void shouldHaveDefaultLocaleWhenNoAcceptLanguageHeader() throws URISyntaxException {
        dispatcher.getProviderFactory().registerProvider(LocaleProvider.class);

        MockHttpRequest request = MockHttpRequest.get("/");
        MockHttpResponse response = new MockHttpResponse();
        dispatcher.invoke(request, response);

        assertEquals("en", response.getContentAsString());
    }
}

即使 LocaleProvider 在我调试时执行 (A) 行,资源也会返回 null

知道为什么@Context 注入在单元测试时不起作用?

【问题讨论】:

    标签: java unit-testing jboss jax-rs resteasy


    【解决方案1】:

    我找到了基于this answer 的解决方案。

    在我的 LocaleProvider 而不是

     dispatcher.getDefaultContextObjects().put(Locale.class, locale);
    

    我需要使用

     ResteasyProviderFactory.pushContext(Locale.class, locale);
    

    希望它可以帮助某人:)

    【讨论】:

    • 谢谢,它有效!!!但是在较新版本的 Resteasy 中,ResteasyProviderFactory.pushContext 方法不再存在。我不得不改用 ResteasyContext.pushContext
    猜你喜欢
    • 2012-10-01
    • 2014-12-04
    • 1970-01-01
    • 2012-02-12
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多