我正在尝试注册一个@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在我调试它时执行了行null
,资源也会返回(A)
。
任何想法为什么@Context注入在单元测试时不起作用?
答案 0 :(得分:2)
我找到了基于this answer的解决方案。
在我的LocaleProvider中而不是
dispatcher.getDefaultContextObjects().put(Locale.class, locale);
我需要使用
ResteasyProviderFactory.pushContext(Locale.class, locale);
希望它可以帮助某人:)