Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
350 views
in Technique[技术] by (71.8m points)

equals - JUnit assertEquals( ) fails for two objects

I created a class and overridden the equals() method. When I use assertTrue(obj1.equals(obj2)), it will pass the test; however, assertEquals(obj1, obj2) will fail the test. Could someone please tell the reason why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My guess is that you haven't actually overridden equals - that you've overloaded it instead. Use the @Override annotation to find this sort of thing out at compile time.

In other words, I suspect you've got:

public boolean equals(MyClass other)

where you should have:

@Override // Force the compiler to check I'm really overriding something
public boolean equals(Object other)

In your working assertion, you were no doubt calling the overloaded method as the compile-time type of obj1 and obj2 were both MyClass (or whatever your class is called). JUnit's assertEquals will only call equals(Object) as it doesn't know any better.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...