一个单元应该如何测试hashCode-equals合约? [英] How should one unit test the hashCode-equals contract?

查看:143
本文介绍了一个单元应该如何测试hashCode-equals合约?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,hashCode契约,根据Java的object.hashCode():

In a nutshell, the hashCode contract, according to Java's object.hashCode():


  1. 哈希代码不应该改变,除非影响equals()变化的东西

  2. equals()意味着哈希码是==

让我们主要关注不可变数据对象 - 它们的信息在构造后永远不会改变,因此假定#1成立。留下#2:问题只是确认等于隐含代码==。

Let's assume interest primarily in immutable data objects - their information never changes after they're constructed, so #1 is assumed to hold. That leaves #2: the problem is simply one of confirming that equals implies hash code ==.

显然,我们无法测试每个可想到的数据对象,除非该集合是平凡的小。那么,编写可能会遇到常见情况的单元测试的最佳方法是什么?

Obviously, we can't test every conceivable data object unless that set is trivially small. So, what is the best way to write a unit test that is likely to catch the common cases?

由于此类的实例是不可变的,因此有限的方法构造这样一个对象;如果可能的话,这个单元测试应该涵盖所有这些。在我的脑海中,入口点是构造函数,反序列化和子类的构造函数(应该可以简化为构造函数调用问题)。

Since the instances of this class are immutable, there are limited ways to construct such an object; this unit test should cover all of them if possible. Off the top of my head, the entry points are the constructors, deserialization, and constructors of subclasses (which should be reducible to the constructor call problem).

[我'我试图通过研究回答我自己的问题。来自其他StackOverflowers的输入是这个过程的一个受欢迎的安全机制。]

[I'm going to try to answer my own question via research. Input from other StackOverflowers is a welcome safety mechanism to this process.]

[这可能适用于其他OO语言,所以我正在添加该标签。]

[This could be applicable to other OO languages, so I'm adding that tag.]

推荐答案

EqualsVerifier 是一个相对较新的开源项目,它在测试equals合同方面做得非常好。它没有来自GSBase的EqualsTester的问题。我肯定会推荐它。

EqualsVerifier is a relatively new open source project and it does a very good job at testing the equals contract. It doesn't have the issues the EqualsTester from GSBase has. I would definitely recommend it.

这篇关于一个单元应该如何测试hashCode-equals合约?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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