如何比较两个这种格式的JAVA嵌套集合List>是否相等

huangapple go评论76阅读模式
英文:

How to compare with optimal effort whether 2 JAVA NESTED COLLECTIONS of this format List<Map<String, Object>> are equal

问题

如何与最佳努力比较两个这种格式的JAVA嵌套集合List&lt;Map&lt;String,Object&gt;&gt;是否相等

List&lt;Map&lt;String,Object&gt;&gt;中,Object可以是ListMap

我需要编写单元测试来比较从json解析的嵌套集合对象与预期值(另一个手动创建的集合)的值。
我可以通过迭代地深入到每个对象,并将它们与另一个集合中的值进行比较来逐步完成此操作。

但是,这种方法似乎非常繁琐,因为我必须迭代每个不同的测试案例。

是否有其他有效的方法?

英文:

How to compare with optimal effort whether 2 JAVA NESTED COLLECTIONS of this format List&lt;Map&lt;String, Object&gt;&gt; are equal

In List&lt;Map&lt;String, Object&gt;&gt; the Object can be List or Map

I need to write unit tests to compare the values of nested collection object parsed from a json and the expected value (another collection which I manually create).
I can do this iteratively by going deep to each of the objects and compare them against the values from the other collection.

But this approach seems to be very tedious since I have to iterate each different test cases.

Is there any other efficient approach?

答案1

得分: 1

这正是assertEquals的用途。

assertEquals(expected, actual);

然而,当出现问题时,这将使调试变得困难。

根据您的代码结构,您可能最好为 JSON 解析部分使用模拟,并仅验证您的代码是否将预期的值传递给解析器。

如果没有其他办法,与其构建第二个集合,为什么不直接断言那里的值呢?如果您是手动“创建”预期集合,您可以改为手动检查返回的集合。

英文:

This is exactly what assertEquals is for.

assertEquals(expected, actual);

The will make it difficult to debug when things go wrong though.

Depending on how your code is structured, you might be better off using a mock for the json parsing part, and validating only that your code is passing in the expected values to the parser.

If nothing else, instead of building up the second collection, why not just assert the values there? If you're manually "creating" the expected collection, you can instead manually check the returned collection.

答案2

得分: 0

正如@Holger指出的那样,这种方式效率不高!

package im.silentsudo.gradletest;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashComparisionTest {

    @AllArgsConstructor
    @NoArgsConstructor
    static class Post {
        Long id;
        String title;
    }

    static private Map<String, Object> generateUser1PostList() {
        final List<ComparisionMain.Post> posts = new ArrayList<>();
        posts.add(new ComparisionMain.Post(1L, "Post 1"));
        posts.add(new ComparisionMain.Post(2L, "Post 2"));
        final Map<String, Object> userPosts = new HashMap<>();
        userPosts.put("user_a", posts);
        return userPosts;
    }

    static private Map<String, Object> generateUser2PostList() {
        final List<ComparisionMain.Post> posts = new ArrayList<>();
        posts.add(new ComparisionMain.Post(20L, "Post 20"));
        posts.add(new ComparisionMain.Post(21L, "Post 21"));
        final Map<String, Object> userPosts = new HashMap<>();
        userPosts.put("user_b", posts);
        return userPosts;
    }

    static private String getHash(String content) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(content.getBytes());
        byte[] digiest = messageDigest.digest();
        return DatatypeConverter.printHexBinary(digiest);
    }

    @Test
    public void testTwoCollectionMeaningfullyEquals() throws NoSuchAlgorithmException {
        System.out.println("------------- testTwoCollectionMeaningfullyEquals --------------");
        final Gson gson = new Gson();
        List<Map<String, Object>> collection1 = new ArrayList<>();
        List<Map<String, Object>> collection2 = new ArrayList<>();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser1PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertEquals(hash1, hash2);

        System.out.println("------------- testTwoCollectionMeaningfullyEquals --------------");
    }

    @Test
    public void testTwoCollectionMeaningfullyNotEquals() throws NoSuchAlgorithmException {
        System.out.println("------------- testTwoCollectionMeaningfullyNotEquals --------------");
        final Gson gson = new Gson();
        List<Map<String, Object>> collection1 = new ArrayList<>();
        List<Map<String, Object>> collection2 = new ArrayList<>();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser2PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertNotEquals(hash1, hash2);

        System.out.println("------------- testTwoCollectionMeaningfullyNotEquals --------------");
    }
}

上述程序的输出为:

Testing started at 12:01 PM ...
> Task :cleanTest
> Task :compileJava UP-TO-DATE
> Task :processResources NO-SOURCE
> Task :classes UP-TO-DATE
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test
------------- testTwoCollectionMeaningfullyNotEquals --------------
766461F7DB37B8EC031BE0145E6832D3
156636D7A2CF2196783F9D644A994391
------------- testTwoCollectionMeaningfullyNotEquals --------------
------------- testTwoCollectionMeaningfullyEquals --------------
766461F7DB37B8EC031BE0145E6832D3
766461F7DB37B8EC031BE0145E6832D3
------------- testTwoCollectionMeaningfullyEquals --------------
BUILD SUCCESSFUL in 0s
4 actionable tasks: 3 executed, 1 up-to-date
12:01:49 PM: Tasks execution finished ':cleanTest :test --tests "im.silentsudo.gradletest.HashComparisionTest"'.

这是一个非常简单的实现。如果你需要在Java中进行对象比较的更多细节,请查看 https://www.baeldung.com/java-equals-hashcode-contracts

英文:

As pointed out by @Holger this is kind of not efficient!

package im.silentsudo.gradletest;

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.junit.Assert;
import org.junit.Test;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashComparisionTest {

    @AllArgsConstructor
    @NoArgsConstructor
    static class Post {
        Long id;
        String title;
    }

    static private Map&lt;String, Object&gt; generateUser1PostList() {
        final List&lt;ComparisionMain.Post&gt; posts = new ArrayList&lt;&gt;();
        posts.add(new ComparisionMain.Post(1L, &quot;Post 1&quot;));
        posts.add(new ComparisionMain.Post(2L, &quot;Post 2&quot;));
        final Map&lt;String, Object&gt; userPosts = new HashMap&lt;&gt;();
        userPosts.put(&quot;user_a&quot;, posts);
        return userPosts;
    }

    static private Map&lt;String, Object&gt; generateUser2PostList() {
        final List&lt;ComparisionMain.Post&gt; posts = new ArrayList&lt;&gt;();
        posts.add(new ComparisionMain.Post(20L, &quot;Post 20&quot;));
        posts.add(new ComparisionMain.Post(21L, &quot;Post 21&quot;));
        final Map&lt;String, Object&gt; userPosts = new HashMap&lt;&gt;();
        userPosts.put(&quot;user_b&quot;, posts);
        return userPosts;
    }

    static private String getHash(String content) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(&quot;MD5&quot;);
        messageDigest.update(content.getBytes());
        byte[] digiest = messageDigest.digest();
        return DatatypeConverter.printHexBinary(digiest);
    }


    @Test
    public void testTwoCollectionMeaningfullyEquals() throws NoSuchAlgorithmException {
        System.out.println(&quot;------------- testTwoCollectionMeaningfullyEquals --------------&quot;);
        final Gson gson = new Gson();
        List&lt;Map&lt;String, Object&gt;&gt; collection1 = new ArrayList&lt;&gt;();
        List&lt;Map&lt;String, Object&gt;&gt; collection2 = new ArrayList&lt;&gt;();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser1PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertEquals(hash1, hash2);

        System.out.println(&quot;------------- testTwoCollectionMeaningfullyEquals --------------&quot;);
    }

    @Test
    public void testTwoCollectionMeaningfullyNotEquals() throws NoSuchAlgorithmException {
        System.out.println(&quot;------------- testTwoCollectionMeaningfullyNotEquals --------------&quot;);
        final Gson gson = new Gson();
        List&lt;Map&lt;String, Object&gt;&gt; collection1 = new ArrayList&lt;&gt;();
        List&lt;Map&lt;String, Object&gt;&gt; collection2 = new ArrayList&lt;&gt;();

        collection1.add(generateUser1PostList());

        collection2.add(generateUser2PostList());

        final String hash1 = getHash(gson.toJson(collection1));

        System.out.println(hash1);
        final String hash2 = getHash(gson.toJson(collection2));
        System.out.println(hash2);

        Assert.assertNotEquals(hash1, hash2);

        System.out.println(&quot;------------- testTwoCollectionMeaningfullyNotEquals --------------&quot;);
    }
}

Output of the above program is:

Testing started at 12:01 PM ...
&gt; Task :cleanTest
&gt; Task :compileJava UP-TO-DATE
&gt; Task :processResources NO-SOURCE
&gt; Task :classes UP-TO-DATE
&gt; Task :compileTestJava
&gt; Task :processTestResources NO-SOURCE
&gt; Task :testClasses
&gt; Task :test
------------- testTwoCollectionMeaningfullyNotEquals --------------
766461F7DB37B8EC031BE0145E6832D3
156636D7A2CF2196783F9D644A994391
------------- testTwoCollectionMeaningfullyNotEquals --------------
------------- testTwoCollectionMeaningfullyEquals --------------
766461F7DB37B8EC031BE0145E6832D3
766461F7DB37B8EC031BE0145E6832D3
------------- testTwoCollectionMeaningfullyEquals --------------
BUILD SUCCESSFUL in 0s
4 actionable tasks: 3 executed, 1 up-to-date
12:01:49 PM: Tasks execution finished &#39;:cleanTest :test --tests &quot;im.silentsudo.gradletest.HashComparisionTest&quot;&#39;.

This is very simple implementation, if you need more details on object comparision in java please take a look at https://www.baeldung.com/java-equals-hashcode-contracts

huangapple
  • 本文由 发表于 2020年5月29日 10:31:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/62077737.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定