如何使用PowerMockito模拟Object.Mapper

我正在尝试使用PowerMockito涵盖My JsonService实用工具类,但是我遇到了异常,并且试图从很长时间内解决此问题,但是仍然无法解决问题,请有人帮我一下。

JsonService

public final class JsonService {
    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

@PrepareForTest({ JsonService.class })
public class JsonServiceTest {
    @Rule
    public PowerMockRule rule = new PowerMockRule();
    static {
        PowerMockAgent.initializeIfNeeded();
    }

    @Test
    public void getObjectFromJsonTest() throws Exception {
        PowerMockito.mockStatic(JsonService.class);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode actualObj = mapper.readTree(jsongString().toString());
        PowerMockito.when(JsonService.getObjectFromJson(jsongString(),JsonNode.class)).thenReturn(actualObj);

    }


    private Object jsongString() {
        String jsonResponse = "{\"content\":{\"status\":\"Success\",\"redirect\":false,\"redirectToModifyFlow\":false,\"response\":"
                + "{\"personalInfo\":{\"status\":\"Success\"}},\"expressCheckoutFlow\":false}}";
        return jsonResponse.toString();
    }

}
评论
mest
mest

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.

点赞
评论