0

I have implemented a method that returns a Connection object.

Now I want to unit test that method and when I make the typical

assertEquals(expectedConnection, actualConnection);

it fails with the error code:

java.lang.AssertionError: expected [org.sqlite.SQLiteConnection@1a968a59] but found [org.sqlite.SQLiteConnection@4667ae56]

I hoped the test passed as, even when the objects are not the same (that's why I haven't used assertSame), they have the same characteristics (have been built in the same way, with the same class atributes)... Is there any way to test Connection objects?

NB: I have the same issue with the unit test of a method that returns a statement

Thanks for your help!!

Arcones
  • 3,954
  • 4
  • 26
  • 46
  • `assertEquals` calls `connection.equals(theOtherConnection)`, that, probably, just compares references (making it same as `assertSame`). Bottom line: you are doing it all wrong. Start with making a statement of what functionality exactly you are trying to assert with this test. – Dima Apr 05 '16 at 22:25
  • @Arcones - From what I see in your output, you are comparing the different **references** in the stack to the (different or same) object in the heap. I would say you should compare the attributes of the connections to get the right assertion. – rafaelbattesti Apr 05 '16 at 22:27

2 Answers2

0

I dont think it is a good idea to create a new connection and compare with actual connection. You could assert user , password, and connection string rather than asserting the actual connection.

I this case it is clear that you are comparing the reference. You can assert only on classes which overrides equals(Object o) from Object class to be precise SQLiteConnection does not override equals method from Object.

Raghu K Nair
  • 3,854
  • 1
  • 28
  • 45
0

assertEquals(expected, actual) uses equals method of the object. And SQLiteConnection inherits it's equals() method from Object class.

Since default equals implementation compares the references to check whether two references, are referencing the same object. This compares is bound to fail. Since in your case, both the references are referencing to different object, hence difference hash code.

You can use ArgumentCaptor instead to capture the values in the actual object and compare them. Here is an example

Community
  • 1
  • 1
user506591
  • 172
  • 2
  • 6