Search code examples
javajunitpowermockito

How to write Junits for ObjectMapper


I am trying to cover My JsonService utility class with Junits but i am getting exception and i am trying to resolve this from long time but still issue not resolved can some one help me please.

JsonService

    public final class JsonService {
        private static final ObjectMapper MAPPER;

private JsonService() {
        // Added to remove sonar issues.
    }

    static {

        log.debug("Start of JsonService static block ");

        MAPPER = new ObjectMapper();
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        MAPPER.setSerializationInclusion(Include.NON_NULL);

        log.debug("End of JsonService static block ");
    }

        public static <T> T getObjectFromJson(final Object jsonString, final Class<T> valueType) {

                // log.debug("Start of JsonService.getObjectFromJson() method.. {}");

                T object = null;
                if (jsonString != null) {
                    try {
                        object = MAPPER.readValue(jsonString.toString(), valueType);
                        // log.debug(DEBUG_LOG_STR, object);
                    } catch (IOException io) {
                        log.error(ERROR_LOG_STR + " in method getObjectFromJson(). Exception Message={}, Exception Stack ={}",
                                io.getMessage(), io);
                        throw new ServiceException(ErrorMessages.JSON_SERIALIZATION_ERROR, io.getCause());
                    }
                }
                // log.debug("End of JsonService.getObjectFromJson() method.. {}");
                return object;
            }
    }

JsonServiceTest

 public class JsonServiceTest {

    @Test
    public void getObjectFromJsonTest() throws Exception {
        // PowerMockito.mockStatic(JsonService.class);
        ObjectMapper mapper = new ObjectMapper();
        TestHelper helper = new TestHelper();
        helper.setName("name");
        helper.setId(1);
        String json = mapper.writeValueAsString(helper);
        TestHelper actual = JsonService.getObjectFromJson(json, TestHelper.class);
        assertEquals(actual.getName(), "name");
        assertEquals(actual.getId(), 1);
    }

    class TestHelper {
        String name;
        long id;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public long getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

    }

}

Exception

com.att.idp.externalpartnerorder.exception.ServiceException
    at com.att.idp.externalpartnerorder.common.util.JsonService.getObjectFromJson(JsonService.java:81)
    at com.att.idp.externalpartnerorder.common.util.JsonServiceTest.getObjectFromJsonTest(JsonServiceTest.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)

Solution

  • No need to mock ObjectMapper try to convert a object of any class type do you have in the code and convert to JSON using ObjectMapper and call the method getObjectFromJson then assert the object properties after that.

    Steps

    1. Create helper pojo test class in
    2. Convert it to json
    3. Call the method and verify the return object
    import static org.hamcrest.CoreMatchers.equalTo;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import java.io.Serializable;
    import org.junit.Assert;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.rules.ErrorCollector;
    import org.junit.rules.ExpectedException;
    import org.junit.rules.RuleChain;
    
    public class JsonServiceTest {
    
        private static final String NAME = "name";
        private static final String TITLE = "title";
        private static final long ID = 1L;
    
        public ErrorCollector collector = new ErrorCollector();
        public ExpectedException expectedException = ExpectedException.none();
    
        @Rule
        public RuleChain ruleChain  = RuleChain.outerRule(collector).around(expectedException);
    
        @Test
        public void getObjectFromJsonTest() throws Exception {
            // Arrange
            ObjectMapper mapper = new ObjectMapper();
            TestHelper helper = new TestHelper();
            helper.setName(NAME);
            helper.setId(ID);
            String json = mapper.writeValueAsString(helper);
    
            // Act
            TestHelper actual = JsonService.getObjectFromJson(json, TestHelper.class);
    
            // Assert
            collector.checkThat(actual.getName(), equalTo(NAME));
            collector.checkThat(actual.getId(), equalTo(ID));
        }
    
        @Test
        public void getExceptionFromJsonTest() throws Exception {
            // Assert
            expectedException.expect(Exception.class);
    
            // Arrange
            ObjectMapper mapper = new ObjectMapper();
            TestExceptionHelper helper = new TestExceptionHelper();
            helper.setTitle(TITLE);
            String json = mapper.writeValueAsString(helper);
    
            // Act
            TestExceptionHelper actual = JsonService.getObjectFromJson(json, TestExceptionHelper.class);
        }
    
        class TestExceptionHelper implements Serializable {
            String title;
    
            public String getTitle() {
                return title;
            }
    
            public void setTitle(String title) {
                this.title = title;
            }
        }
    
        static class TestHelper implements Serializable {
            String name;
            long id;
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
    
            public long getId() {
                return id;
            }
    
            public void setId(long id) {
                this.id = id;
            }
        }
    
    }