• Post Reply Bookmark Topic Watch Topic
  • New Topic

JUnit assertEquals to compare 2 objects  RSS feed

 
Conor Niall
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I'm trying to find a way to use JUnit testing to write an assert statement that will compare two objects and make sure they are the same. In my main method, I am randomly generating one of 2 subclasses based on generating and assigning them a random number. If random number is 0, then create SubClassA. If random number is 1, then create SubClassB.
I have tried:

When I run the test it fails with the message:

What am I doing wrong? Or is there another way to test this?
 
Knute Snortum
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just a guess but do you have equals() and hashCode() setup in SubClassA?
 
Conor Niall
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Knute Snortum wrote:Just a guess but do you have equals() and hashCode() setup in SubClassA?


No I do not have these setup in SubClassA
 
Knute Snortum
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then I think assertEquals() uses Object#equals() to compare with and then the two object references will not be equal unless they point to the very same object.  Is that what you want?

If not, I would override equals() and hashCode() in SubClassA.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see the point of using random here. Why are you doing that?
 
Conor Niall
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ended up using:

Seems to do what I want it to do.
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Conor Niall wrote:I ended up using:

Seems to do what I want it to do.

Sorry, but that doesn't have any contextual connection to the code you posted previously, leaving gaps that nobody else but you can fill in to make this thread anywhere near coherent.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!