单元测试resteasy时未注入@Context对象

@Context object not injected when unit testing resteasy

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

按照文章 http://bill.burkecentral.com/2011/03/09/adding-objects-that-are-context-injectable/ 我设法获得了提供商 运行ning

@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());
    }
}

资源 returns null 即使 LocaleProvider 在我调试时执行行 (A)

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

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

在我的 LocaleProvider 而不是

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

我需要使用

 ResteasyProviderFactory.pushContext(Locale.class, locale);

希望对大家有所帮助:)