1

Имеется статический метод getPatches(Object, Object) в публичном классе JsonUtil который тестируется с помощью JUnit 4.12 на Eclipse 2021-09:

import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public static List<PatchOperation> getPatches(
    @Nonnull Object oldData,
    @Nonnull Object newData)
    throws IOException
{
    List<PatchOperation> _patchOperations = new ArrayList<>();
    ObjectMapper objectMapper = new ObjectMapper();

    String _oldDataJson = objectMapper.writeValueAsString(oldData);
    String _newDataJson = objectMapper.writeValueAsString(newData);

    JsonNode _oldJsonNode = objectMapper.readTree(_oldDataJson);
    JsonNode _newJsonNode = objectMapper.readTree(_newDataJson);

    JsonNode _patchData = com.github.fge.jsonpatch.diff.JsonDiff.asJson(_oldJsonNode, _newJsonNode);
    if (_patchData != null)
    {
        _patchOperations = objectMapper.convertValue(_patchData, new TypeReference<List<PatchOperation>>(){});
    }

    return _patchOperations;
}

Здесь, PatchOperation просто POJO класс для де/-сериализации JSON-Patch (см. RFC6902), который используется в PATCH-запросах к серверу:

import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PatchOperation implements Serializable
{
    private static final long serialVersionUID = 9999999999999999999L;
    
    @JsonProperty("op")
    public String Operation;
    
    @JsonProperty("path")
    public String Path;
    
    @JsonProperty("value")
    public Object Value;
    
    @JsonProperty("from")
    public String From;
    
    @Override
    public String toString() 
    {
        try
        {
            return new ObjectMapper().writeValueAsString(this);
        }
        catch ( JsonProcessingException e )
        {
            return super.toString();
        }
    }
}

JUnit тест для метода getPatches:

@Test public final void getPatchesTest()
            throws JsonProcessingException, IOException
{
    PatchTestItem _itemOne = new PatchTestItem();
    _itemOne.id = "ABC123";
    _itemOne.active = true;
    _itemOne.value = "First value";

    PatchTestItem _itemTwo = new PatchTestItem();
    _itemTwo.id = "ABC123";
    _itemTwo.active = true;
    _itemTwo.value = "Updated value";

    java.util.List<PatchOperation> _patches = JsonUtil.getPatches(_itemOne, _itemTwo);

    Assert.assertNotNull(_patches);
    Assert.assertEquals(1, _patches.size());
    // в следующей строке выбрасывает ошибку при тестировании обобщённого метода
    Assert.assertEquals("replace", _patches.get(0).Operation);
    Assert.assertEquals("/value", _patches.get(0).Path);
    Assert.assertEquals(_itemTwo.value, _patches.get(0).Value.toString());
    
    _itemTwo.value = _itemOne.value;
    _patches = JsonUtil.getPatches(_itemOne, _itemTwo);
    
    Assert.assertNotNull(_patches);
    Assert.assertEquals(0, _patches.size());
    
    _itemTwo.active = false;
    _itemTwo.value = "Updated value again";
    _patches = JsonUtil.getPatches(_itemOne, _itemTwo);
    
    Assert.assertNotNull(_patches);
}

Тест выполняется и в таком виде всё нормально.
Теперь было решено использовать обобщённый метод следующим образом:

public static <T> List<T> getPatches(
    @Nonnull Object oldData,
    @Nonnull Object newData)
    throws IOException
{
    List<T> _patchOperations = new ArrayList<>();
    ObjectMapper objectMapper = new ObjectMapper();

    String _oldDataJson = objectMapper.writeValueAsString(oldData);
    String _newDataJson = objectMapper.writeValueAsString(newData);

    JsonNode _oldJsonNode = objectMapper.readTree(_oldDataJson);
    JsonNode _newJsonNode = objectMapper.readTree(_newDataJson);

    JsonNode _patchData = com.github.fge.jsonpatch.diff.JsonDiff.asJson(_oldJsonNode, _newJsonNode);
    if (_patchData != null)
    {
        _patchOperations = objectMapper.convertValue(_patchData, new TypeReference<List<T>>(){});
    }

    return _patchOperations;
}

Вышеприведённый вариант не проходит тест - выдаёт ошибку "Source not found" и в лог вываливается:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx.xxx.xxx.xxx.xxx.PatchOperation
    at xxx.xxx.xxx.xxx.xxx.JsonUtilTest.getPatchesTest(JsonUtilTest.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    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:93)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

Я конечно понимаю, что проблема заключается в том, что JUnit не может найти тип, но как и что мне изменить, чтоб тест выполнялся?

4
  • JsonUtilTest.java:36 это что за строчка в тесте? 1 окт 2021 в 9:46
  • Проблема в этом месте objectMapper.convertValue(_patchData, new TypeReference<List<T>>(){}). Тут в runtime у objectMapper нет информации о типе элемента в который, нужно конвертировать json. Т.е. он не знает, что нужно создавать объект типа PatchOperation. И он создает то, что может LinkedHashMap. Ну и потом уже проблема в тесте при попытке использовать объект как PatchOperation. У вас 100% есть warning-и компилятора (они то и говорят, что код небезопасный) 1 окт 2021 в 9:55
  • @RomanKonoval и что делать? как быть? Как передать "информацию о типе элемента"? Правильно ли я понимаю, что это никоим образом не связано с самим тестом? Или код метода при компиляции/дебаге будет работать?
    – XelaNimed
    1 окт 2021 в 10:20
  • Проблема не в тесте. Проблема в коде (выше я написал где именно). Можно ли jackson маперу передать информацию о типе динамически, я не знаю, нужно смотреть. Простой и тупой метод это передавать явно TypeReference аргументом в getPatches, так чтоб в месте вызова был точный тип: JsonUtil.getPatches(_itemOne, _itemTwo, LIST_OF_PATCH_OPERATIONS_TYPE); ну и определить константу LIST_OF_PATCH_OPERATIOS_TYPE = new TypeReference<List<PatchOperation>>(){} 1 окт 2021 в 10:42

1 ответ 1

0

Спасибо Роману, за разъяснения и помощь. По предложению @RomanKonoval в метод был добавлен параметр, которым и передаётся требуемая информация о типе:

public static <T> T getPatches(
    @Nonnull Object oldData,
    @Nonnull Object newData,
    final TypeReference<T> typeRef)
    throws IOException
{
    String _oldDataJson = objectMapper.writeValueAsString(oldData);
    String _newDataJson = objectMapper.writeValueAsString(newData);

    JsonNode _oldJsonNode = objectMapper.readTree(_oldDataJson);
    JsonNode _newJsonNode = objectMapper.readTree(_newDataJson);

    JsonNode _patchData = com.github.fge.jsonpatch.diff.JsonDiff.asJson(_oldJsonNode, _newJsonNode);
    return new ObjectMapper().convertValue(_patchData, typeRef);
}
// Пример использования:
// final TypeReference<List<PatchOperation>> _typeRef =
//       new TypeReference<List<PatchOperation>>() {};
// List<PatchOperation> _patches =
//       JsonUtil.getConvertedPatch(_itemOne, _itemTwo, _typeRef);

Буду рад конструктивной критике и замечаниям.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.