比较忽略给定字段的地图 [英] Compare maps ignoring given fields

查看:52
本文介绍了比较忽略给定字段的地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得这里缺少明显的东西,但是文档让我失望了.我正在尝试比较两个映射,而忽略assertJ中的一组字段.我想看看这个断言的通行证:

I feel like I'm missing something obvious here, but the documentation is letting me down. I'm attempting to compare two maps while ignoring a set of fields in assertJ. I would like to see this assert pass:

  private static final String[] IGNORED_FIELDS = { "ignored", "another" };
  private static final Map<String, Object> TEST_PAYLOAD = ImmutableMap.of("test", "payload", "example", "value", "ignored", "field");
  private static final Map<String, Object> COMPARISON_PAYLOAD = ImmutableMap.of("test", "payload", "example", "value", "another", "ignored field");
  // assert fails
  assertThat(TEST_PAYLOAD).isEqualToIgnoringGivenFields(COMPARISON_PAYLOAD, IGNORED_FIELDS);

但是,实际发生的比较是针对地图对象的,并且在大小,modCount,阈值等方面失败,此外,在比较表,键和值时,它实际上并不会忽略列出的字段.我也尝试过使用

However, the comparison that actually occurs is of the map objects, and fails on things like size, modCount, threshold, etc. In addition, it doesn't actually ignore the fields listed when comparing tables, keys, and values. I have also tried using

  assertThat(TEST_PAYLOAD).usingRecursiveComparison().ignoringGivenFields(IGNORED_FIELDS).isEqualTo(COMPARISON_PAYLOAD);

,但这失败了,因为它试图比较被忽略的字段.这里有一个优雅的解决方案,还是我必须手动遍历键?

but this failed because it attempted to compare the ignored fields. Is there an elegant solution here, or am I going to have to manually iterate through keys?

推荐答案

ignoringGivenFields()不起作用,因为它是 ObjectAssert ,而不是 MapAssert方法,并且操作对象的属性,而不是您指出的地图键.

ignoringGivenFields() won't work, because it's an ObjectAssert, not a MapAssert method and operates on object's properties, not map's keys, as you pointed out.

也就是说,我相信没有可以使用的内置AssertJ方法,但是您可以编写自己的过滤器方法并在进行相等性测试之前应用它:

That said, I believe there's no built-in AssertJ method which you could use, but you can write your own filter method and apply it before doing equality test:

private static <V> Map<String, V> filterIgnoredKeys(Map<String, V> map) {
    return Maps.filterKeys(map, key -> !IGNORED_FIELDS.contains(key));
}
// later
assertThat(filterIgnoredKeys(TEST_PAYLOAD))
        .isEqualTo(filterIgnoredKeys(COMPARISON_PAYLOAD))

如果您希望解决方案更优雅,可以尝试

If you want the solution to be more elegant, you can experiment with your own custom assertion.

这篇关于比较忽略给定字段的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆