junit 如何比较一个对象和一个数组?

5f0d552i  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(140)

下面的代码是Object的一个示例,它实际上是一个字符串数组:

private final Map<String, Object> tokenPayload = // assume map is populated
tokenPayload.get("aud") // gives me instance of Object

它本质上是一个JWT,它有一个如下所示的aud声明:

{
  "aud": [
    "https://www.example.com"
  ],
}

我尝试添加一个简单的JUnitAssert:

assertArrayEquals(new String[] {"https://www.example.com"}, (Object[])tokenPayload.get("aud"));

但我得到了一个强制转换异常ClassCast class java.util.ArrayList cannot be cast to class [Ljava.lang.String; (java.util.ArrayList and [Ljava.lang.String; are in module java.base of loader 'bootstrap')
什么是最好的测试方法?

6qfn3psc

6qfn3psc1#

下面是一个包含使用Hamcrest的Assert的示例,如www.example.com所述ip.java

@Test
    public void testArrayComparison() throws Exception {
        String json = "{\"aud\": [\"https://www.example.com\",\"https://www.example.biz\"]}";

        Map<String, Object> map = new ObjectMapper().readValue(json, Map.class);

        List<Object> aud = (List<Object>) map.get("aud");

        Object[] expected = new Object[] {"https://www.example.biz","https://www.example.com"};

        assertThat(aud, containsInAnyOrder(expected));
    }

相关问题