比较两个对象时,JUnit assertEquals()不起作用 [英] JUnit assertEquals() not working when comparing two objects

查看:149
本文介绍了比较两个对象时,JUnit assertEquals()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试摆脱Java的困扰.单元测试对我来说非常重要,因此最近我开始使用JUnit.一开始很难,但我已经掌握了.至此为止,我所有的测试都进行了工作,除了比较同一个类的两个对象(我没有尝试测试创建另一个类的对象的函数).基本上,当我在类中有一个创建该类新实例的方法并尝试测试该方法时,会收到一个奇怪的错误.

I'm trying to get the hang of Java. Unit testing is pretty important to me and so recently I've started to use JUnit. It was tough to begin with but I'm getting the hang of it. All of my tests have worked up to this point, with the exception of comparing two objects of the same class (I haven't tried testing a function that creates an object of a different class). Basically, when I have a method within a class that creates a new instance of the class, and I try to test the method, I get a weird error.

"expected:runnersLog.MTLog@433c675d,但是runnersLog.MTLog@3f91beef"

"expected:runnersLog.MTLog@433c675d but was runnersLog.MTLog@3f91beef"

我尝试研究此问题,但没有发现任何帮助. 这里是指向我在github上的课程的链接.我尝试测试的方法是mt()方法,而测试类是ILogTest.

I have tried researching this problem, but haven't found anything of much help. Here's the link to my classes on github. The method I am trying to test is the mt() method, and the test class is ILogTest.

这不是我遇到此问题的唯一情况.对于任何具有返回相同类的新对象的方法的类,我都会收到完全相同的3f91beef错误(即使对象更复杂-带参数)

This is not the only case where I am having this problem. With any class that has a method that returns a new object of the same class, I am getting this exact same 3f91beef error (even when the object is more complicated - with arguments)

推荐答案

assertEquals将对每个要比较的对象使用Object#equals.看来您的类ILogTest不会覆盖equals方法,因此调用Object#equals只会将引用本身进行比较,并且由于它们是不同的对象引用,因此结果将为false.

assertEquals will use Object#equals for each object being compared. Looks like your class ILogTest doesn't override equals method, so calling Object#equals will just compare the references by itself, and since they're different object references, the result will be false.

您有两个选择:

  1. 覆盖ILogTest中的public boolean equals(Object o).
  2. 在实现equals方法的相关字段上使用assertEquals,例如StringIntegerLong等.此代码需要更多代码,但在无法修改所声明的类时很有用.
  1. Override public boolean equals(Object o) in ILogTest.
  2. Use assertEquals on the relevant fields that implement equals method e.g. String, Integer, Long, etc. This one requires more code but is useful when you cannot modify the class(es) being asserted.

这篇关于比较两个对象时,JUnit assertEquals()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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