Reputation: 668
I'm trying to register a @Provider which would inject Locale object into the @Context so that I can reuse it in my REST resources.
Following the article http://bill.burkecentral.com/2011/03/09/adding-objects-that-are-context-injectable/ I managed to get the provider running
@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));
}
}
And use it like this
@Path("/")
public class Resource {
@GET
public String get(@Context Locale locale) {
if (locale == null) {
return "null";
}
return locale.getLanguage();
}
}
The code so far works great when deployed to Tomcat. But I run into an issue when I try to unit test it. I have
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());
}
}
The Resource returns null
even though the LocaleProvider executes the line (A)
if I debug it.
Any idea why the @Context injection does not work when unit testing?
Upvotes: 4
Views: 2685
Reputation: 668
I found a solution based on this answer.
In my LocaleProvider instead of
dispatcher.getDefaultContextObjects().put(Locale.class, locale);
I needed to use
ResteasyProviderFactory.pushContext(Locale.class, locale);
Hope it helps someone :)
Upvotes: 4