assertj: usingRecursiveComparison() returns false positive when comparing to a Spring Data JPA projection

  • spring-boot-starter-parent version: 3.3.2 (with managed dependency versions)
  • assertj core version: 3.25.3
  • java version: 17
  • test framework version: junit-jupiter-api 5.10.3

Test case reproducing the bug

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepo extends JpaRepository<PersonRepo.PersonEntity, String> {
    @Entity
    public static class PersonEntity {
        @Id
        private String name;
    }

    public interface Person {
        String getName();
    }

    @Query(value = "SELECT 'alice' as name")
    Person getPerson();
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

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

@DataJpaTest
@AutoConfigureTestDatabase(replace = Replace.NONE)
public class PersonRepoTest {
    @Autowired
    private PersonRepo personRepo;

    private record PersonImpl(String getName) implements PersonRepo.Person {
    }

    @Test
    public void test() {
        PersonRepo.Person alice = personRepo.getPerson();
        PersonRepo.Person bob = new PersonImpl("bob");
        // Recursive comparison incorrectly asserts that alice and bob are the same
        assertThat(alice).usingRecursiveComparison().isEqualTo(bob);
    }
}

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 1
  • Comments: 17 (12 by maintainers)

Commits related to this issue

Most upvoted comments

I still wonder how to improve the user experience for the original example…

We could throw some misconfiguration exception in case the object under test is a proxy (detected via Proxy.isProxyClass()), no fields are found and expected is not a proxy. Kind of similar to how Mockito fails when stubbing is not done correctly.

WDYT?

I couldn’t find any straightforward way to identify the “good” interface that the proxy implements so I made it work with a custom introspection strategy that identifies the properties to check based on a given type:

@Test
public void test() {
    Person alice = personRepo.getPerson();
    Person bob = new PersonImpl("bob");

    assertThat(alice)
        .usingRecursiveComparison()
        .withIntrospectionStrategy(new ComparingTypeProperties(Person.class))
        .isEqualTo(bob);
}

static class ComparingTypeProperties extends org.assertj.core.api.recursive.comparison.ComparingProperties {

    private static final String GET_PREFIX = "get";
    private static final String IS_PREFIX = "is";

    private final Map<Class<?>, Set<String>> propertiesNamesPerClass = new ConcurrentHashMap<>();

    private final Class<?> type;

    ComparingTypeProperties(Class<?> type) {
        this.type = type;
    }

    @Override
    public Set<String> getChildrenNodeNamesOf(Object node) {
        if (node == null) {
            return new HashSet<>();
        }
        if (type.isInstance(node)) {
            return propertiesNamesPerClass.computeIfAbsent(type, ComparingTypeProperties::getPropertiesNamesOf);
        }
        throw new IllegalArgumentException();
    }

    // code below copy-pasted from ComparingProperties due to private/package-private access

    private static Set<String> getPropertiesNamesOf(Class<?> clazz) {
        return gettersIncludingInheritedOf(clazz).stream()
            .map(Method::getName)
            .map(ComparingTypeProperties::toPropertyName)
            .collect(toSet());
    }

    private static String toPropertyName(String methodName) {
        String propertyWithCapitalLetter = methodName.startsWith(GET_PREFIX)
                ? methodName.substring(GET_PREFIX.length()) : methodName.substring(IS_PREFIX.length());
        return propertyWithCapitalLetter.toLowerCase().charAt(0) + propertyWithCapitalLetter.substring(1);
    }

}

The example now fails with:

java.lang.AssertionError: 
Expecting actual:
  org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap@c7d173f
to be equal to:
  PersonImpl[getName=bob]
when recursively comparing field by field, but found the following difference:

field/property 'name' differ:
- actual value  : "alice"
- expected value: "bob"

This is just to spark further discussion, I’m not saying you should try this at home 😄