Kotlin class instance assert not correct

Home / Uncategorized / Kotlin class instance assert not correct

I’m converting a Java project into Kotlin. I’ve converted a User object into Kotlin and when I run the existing JUnit tests in Java I’m getting a error between two instances of the Kotlin User object.

User.kt:data class User (
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
var id: Long? = null,


import static org.assertj.core.api.Assertions.assertThat;

public class TestUtil {
public static void equalsVerifier(Class clazz) throws Exception {
Object domainObject1 = clazz.getConstructor().newInstance();
// Test with an instance of the same class
Object domainObject2 = clazz.getConstructor().newInstance();

The assertThat(domainObject1).isNotEqualTo(domainObject2) test fails, as I believe in Java comparison is not done correctly on the Kotlin class. If I run this through a debugger, I can see that domainObject1 and domainObject2 are different instances.

Is it possible to get this test case to pass? The same test case is used for other Java classes, so it has to work for both Java and Kotlin classes.

The isNotEqualTo calls equals. The Kotlin class implements correct equals method for data class. So domainObject1.equals(domainObject2) is true. This behavior is correct.

just look at the AssertJ document:isNotSameAs(Object other):
Verifies that the actual value is not the same as the given one,
ie using == comparison.

I think you should try:assertThat(domainObject1).isNotSameAs(domainObject2);
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *