JUnit assertEquals() not working when comparing two objects

后端 未结 3 1968
萌比男神i
萌比男神i 2020-12-19 07:32

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

3条回答
  •  眼角桃花
    2020-12-19 07:55

    You need to overrride equals, the equals method in the superclass Object checks for references if both references point to the same object equals is true if not false, so you need to write down an equals method that will check your objects content and check if the values are the same, it is also recommended that you override your hashCode method too.

    An example could 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 learn more you could check: Why do I need to override the equals and hashCode methods in Java?

提交回复
热议问题