[英]How to unit test a class to check it can be used in a Set or Map (i.e. contains always works)
I discovered that some instance of a (java) class that I used in Maps and Sets sometimes fails to be found using the contains
method. 我发现有时无法使用
contains
方法找到我在Maps和Sets中使用的(java)类的某些实例。
The problem was simply that the class did not implement "hashCode" (but it has equals
). 问题很简单 ,就是该类未实现“ hashCode”(但具有
equals
)。 And the subtlety was that it actually works most of the time: I only found out about the error when running some code with concurrency. 精妙之处在于它实际上在大多数情况下都有效:我只有在并发运行某些代码时才发现有关该错误的信息。
My problem now is that I'd like to make a unit test that assert that this class can be used reliably in a Set/Map (ie that .contains
works) but I cannot reproduce the bug. 我现在的问题是,我想做一个单元测试,断言该类可以在Set / Map中可靠地使用(即
.contains
有效),但我无法重现该错误。
As I say, almost all the time it actually works. 就像我说的那样,它几乎一直都在起作用。 I tried to make a Set of a couple of instances, then run multiple times
contains
with copies of these instances, in parallel. 我尝试制作几个实例的集合,然后并行运行
contains
这些实例的副本的多次。 But it always works. 但是它总是有效的。
What test of mySet.contains(item-copy)
would fails for sure if item class has not hashCode
? 如果项目类没有
hashCode
,则mySet.contains(item-copy)
哪种测试将失败?
Here is the test pseudo code that don't fails when MyItem
does not implements hashCode: 这是当
MyItem
不实现hashCode时不会失败的测试伪代码:
def testFindInSet(): Unit ={
val items = Seq(---list of args---).map( args => new MyItem(args)}.toSet
items.par.foreach{ item =>
(1 to 100).par.foreach{ k =>
val itemCopy = new MyItem(item) // that's a copy constructor
assertTrue("item not found", items.contains(itemCopy))
}
}
}
I tried to make a Set of a couple of instances
我尝试制作一组实例
Scala has specialized representations for sets up to 4 elements instead of using HashSet
. Scala具有专门的表示形式 ,最多可以设置4个元素,而不是使用
HashSet
。 I expect making a larger set or using HashSet
explicitly should be enough to make it fail. 我希望做出更大的设置或显式使用
HashSet
应该足以使它失败。 But it's simpler just to compare hashCode
of copies: assertTrue("hashCode not implemented", itemCopy.hashCode == item.hashCode)
. 但是,仅比较副本的
hashCode
更为简单: assertTrue("hashCode not implemented", itemCopy.hashCode == item.hashCode)
。 If this fails, the contract is already broken (assuming itemCopy == item
). 如果失败,则合同已被破坏(假设
itemCopy == item
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.