Serg M Ten
Serg M Ten

Reputation: 5606

How to simulate a CDI @Produces annotation on a JUnit

I am writing a JUnit test for a class which does something like:

org.glassfish.jersey.client.JerseyClient client = getHTTPClient(SSLContextFactory.getContext(), connectTimeout, readTimeout, true);
client.register(CustomJAXBContextProvider.class); // subclass of javax.ws.rs.ext.ContextResolver<JAXBContext>
client.property(MarshallerProperties.JSON_INCLUDE_ROOT, true);
WebTarget webTarget = client.target(contextPath);
Response response = webTarget.request(MediaType.APPLICATION_JSON.get()
return response.readEntity(ResponseModel.class);

The application runs inside a WebLogic container and has another class with a CDI @Produces annotation:

public class ObjectMapperProvider {
    private ObjectMapper objectMapper;

    @Produces
    public ObjectMapper objectMapper() {
        objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JSR310Module());
        objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
        return objectMapper;
    }
}

When I run the JUnit test from outside WebLogic I get an error

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "fieldName" (class ResponseModel), not marked as ignorable

Because the JSON response contains a field which is not declared in the model and the JUnit is not obtaining the ObjectMapper through the @Produces annotation but getting a default one. The JAXBContext is EclipseLink MOXy.

My question is: How do I get the code tested by my JUint to instantiate ObjectMapper as returned from ObjectMapperProvider instead of a default one lacking the DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false?

Upvotes: 0

Views: 214

Answers (1)

Jonathan S. Fisher
Jonathan S. Fisher

Reputation: 8886

We cover this exact scenario using Mockito. Depending on how JaxBContext is created, you could use a spy to return a mock. Without posting your complete test code and the class under test, it's hard to give a more complete answer than that.

Upvotes: 0

Related Questions