How do I assert equality on two classes without an equals method?

后端 未结 23 1559
臣服心动
臣服心动 2020-11-28 05:20

Say I have a class with no equals() method, to which do not have the source. I want to assert equality on two instances of that class.

I can do multiple asserts:

23条回答
  •  情深已故
    2020-11-28 05:47

    Some of the reflection compare methods are shallow

    Another option is to convert the object to a json and compare the strings.

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;    
    public static String getJsonString(Object obj) {
     try {
        ObjectMapper objectMapper = new ObjectMapper();
        return bjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
         } catch (JsonProcessingException e) {
            LOGGER.error("Error parsing log entry", e);
            return null;
        }
    }
    ...
    assertEquals(getJsonString(MyexpectedObject), getJsonString(MyActualObject))
    

提交回复
热议问题