JUnit assertEquals () does not work when comparing two objects

I am trying to get Java. Unit testing is very important to me, and recently I started using JUnit. It was hard to start from the start, but I get stuck on it. All my tests have worked up to this point, with the exception of comparing two objects of the same class (I have not tried to test a function that creates an object of another class). Basically, when I have a method inside the class that creates a new instance of the class, and I try to test the method, I get a strange error.

": runnersLog.MTLog@433c675d , but there were runnersLog.MTLog@3f91beef "

I tried to study this problem, but did not find anything useful. Here is a link to my github classes. The method I'm trying to test is the mt() method, and the test class is ILogTest .

This is not the only case when I have this problem. With any class that has a method that returns a new object of the same class, I get this same 3f91beef error (even if the object is more complex - with arguments)

+5
source share
3 answers

assertEquals will use Object#equals for each compared object. It seems your ILogTest class ILogTest not override the equals method, so calling Object#equals will just compare the links on their own, and since they are different object references, the result will be false.

You have two options:

  • Override public boolean equals(Object o) in ILogTest .
  • Use assertEquals in the appropriate fields that implement the equals method, for example. String , Integer , Long , etc. This requires more code, but it is useful if you cannot change the class (s) to be validated.
+7
source

If you use a modern development environment for development (for example, Eclipse, IntelliJ, etc.), they can generate these methods for you. Check this for two reasons: 1) to save time 2) To prevent possible errors.

In the eclipse IDE, you can do this by choosing source -> generate hashCode () and equals ().

One more thing, when you implement of these two, you must implement the other.

+2
source

You need to override equals, the equals method in the Object superclass checks links if both links point to the same object equal to true, if not false, so you need to write an equals method that will check the contents of your objects and check if the values ​​match, It is also recommended that you override the hashCode method.

An example would be:

 Custom a= new Custom(""); Custom b= a; //b would be equal a. because they reference the same object. Custom c= new Custom(""); //c would not be equal to a, although the value is the same. 

to find out more, you can check: Why do I need to override the equals and hashCode methods in Java?

+2
source

All Articles