用于 bean 比较的单元测试框架
有没有什么好的框架来比较整个对象?
现在,
assertEquals("[email protected]", obj.email);
assertEquals("5", obj.shop);
如果返回错误的电子邮件,我永远不知道它是否有正确的商店,我想获得不正确字段的列表。
Is there any good framework for comparing whole objects?
now i do
assertEquals("[email protected]", obj.email);
assertEquals("5", obj.shop);
if bad email is returned i never get to know if it had the right shop, i would like to get a list of incorrect fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
按照 1 个测试、1 个断言的思路,如果您在自己的测试中包含每个断言,您就会知道其中一个或两个断言是否失败,因为有 1 或 2 个失败的测试。
显然,您需要将对象的设置移至方法中,使其在测试设置方法中执行,并将其设置为类变量。
如果您实际上想测试所有属性是否都在单个测试中设置:
但我不确定这会给您带来什么。
但如果你真的想比较整个对象的相等性,那么重写 equals 方法(不要忘记 getHashCode)并在那里进行相等性检查。毕竟这就是它的用途...
如果您想要一个不正确字段的列表,您可以使 equals 方法填充一个内部列表,如果相等性检查失败,您可以查询该内部列表,以获取上次相等性失败的字段列表被检查了。不过,我真的不认为这是一个好主意。
Going with the 1 test, 1 assert line of thinking if you has each assert in its own test you would know if one or both of these had failed by the fact that there were 1 or 2 failing tests.
obviously you need to move the setup of the object into a method ot have it performed in the test set up method and have it a class variable.
If you actually want to test if all properties are set in a single test:
but I'm not sure what this gives you really.
But if you really want to compare the whole objects equality then override the equals method (not forgetting getHashCode too) and do your equality checking in there. after all that is what it is for...
If you want a list of incorrect fields you could make the equals method populate an internal list which you could query if the equality check failed, to get the list of failed fields the last time equality was checked. Don't really think that's a good idea though.
您还可以实现类似的接口。
http://java.sun.com/ j2se/1.5.0/docs/api/java/lang/Comparable.html
You can also implement the comparable interface.
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html
这对我有帮助
如何测试复杂对象图的相等性?
this has helped me with that
How to test for equality of complex object graphs?
我会选择 hamcrest 匹配器。它们允许我编写这样的代码:
I would go for hamcrest matchers. They allow me to write code like this:
如果你想测试对象相等性,那么你肯定需要实现 equals() 并使用 assertEquals() 进行测试,但除此之外 Sam 是正确的,每个测试一个断言
If you want to test object equality, then surely you need to implement equals() and test using assertEquals(), but otherwise Sam is correct, one assertion per test