lundi 9 mars 2015

@Context object now injected when unit testing resteasy

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://ift.tt/1MmqMdg 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?


Aucun commentaire:

Enregistrer un commentaire