如何为ObjectMapper编写Junits?

问题描述 投票:0回答:1

我试图用Junits覆盖我的JsonService实用类,但我得到了异常,我试图解决这个问题,从很长一段时间,但仍然问题没有解决,一些人可以帮助我,请。

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;
        }

    }

}

异常情况

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)
java junit powermockito
1个回答
1
投票

不需要模拟 ObjectMapper 尝试转换任何类类型的对象,你有在代码和转换为JSON使用ObjectMapper和调用的方法 getObjectFromJson 然后再断言对象的属性。

步骤

  1. 创建帮助pojo测试类
  2. 将其转换为json
  3. 调用该方法并验证返回对象
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;
        }
    }

}

© www.soinside.com 2019 - 2024. All rights reserved.