当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Unit Test for a method that returns a Connection object

问题描述:

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

[[email protected]] but found

[[email protected]]

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!!

网友答案:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: