在Java测试框架中使用自定义equals方法断言两个集合是相等的 [英] Assert two collections are equal using custom equals method in Java test frameworks

查看:364
本文介绍了在Java测试框架中使用自定义equals方法断言两个集合是相等的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,该类仅使用id属性定义了等于.它还有另一个方法(称为"areSame"),该方法检查给定的参数是否具有与该对象的属性相同的重要属性(并且不考虑id).

I have class, which defines equals just using id attribute. It also has another method (called "areSame"), which checks if the given argument has some important properties equal to this objects properties (and it disregards id).

在测试中,我想使用areSame as"custom equals"方法来检查两个集合是否相同 (最好忽略顺序,而不必依赖hashCode,这显然与areSame不一致).

In test, I'd like to check, if two collections are same using the areSame as "custom equals" method (preferably ignoring order and without relying on hashCode, which is inconsistent with areSame, obviously).

我想知道,是否有更短的方法然后编写包装器.写这样的东西会更令人愉快

I was wondering, if there is shorter way then writing a wrapper. It'd be more pleasant to write something like

assertThat(actualCollection, 
containsInAnyOrder_butUsingCustomEquals(expectedCollection, "areSame")); 

Hamcrests示例,在处理集合时,仅使用简单类型,并且虽然可以比较诸如reflectEquals之类的对象,但我还没有弄清楚如何组合匹配器来完成我想要的事情.

Hamcrests examples, when dealing with collections, only use simple types and while there are possibilities for comparing objects like reflectEquals, I haven't figured out how to combine matchers to do what I want.

我使用的是JUnit,因此Hamcrest似乎是第一选择,因为JUnit已经包含了一些匹配器.但是由于我还没有束缚,我想使用AssertJ,Mockito或其他框架的解决方案是可以接受的.

I'm using JUnit, so Hamcrest seemed to be first joice as JUnit already contains some of its matchers. But as I'm not tied to it yet, I guess that solution using AssertJ, Mockito or other framework would be acceptable.

那么,这在某些测试框架中是否可行,还是我应该对其进行总结?

So, is this doable in some testing framework or should I wrapp it up?

由于我漫长的搜索并没有消除任何人甚至没有成功询问此问题的原因,所以我想大多数人都不会浪费时间来烦恼另外几行,而只是编写包装器和工厂来转换集合,对吗?希望我没有错过谷歌...

Since my quite long search didn't reaveal anyone even unsuccessfuly asking about this, I guess most people don't waste time agonizing over few more lines and just write the wrapper and factory to convert collection, right? Hope I haven't missgoogled...

推荐答案

自定义比较策略

assertj is good at this, especially its custom-comparison-strategy

assertThat(actual).usingElementComparator(customComparator).containsOnlyElementsOf(expectedCollection);

或更方便(无需使用预期的元素进行收集)

or more convenient (no need to make a collection with expected elements)

assertThat(actual).usingElementComparator(customComparator).containsOnly(expected1, expected2);

这篇关于在Java测试框架中使用自定义equals方法断言两个集合是相等的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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