javaspring-data-jpajunit5

How to test JPA Specification


I have a builder that create a JPA Specification according to filters. How do I test the builder ? assertEquals method always return false when comparing Specifications...

I already try to call Specification::toPredicate method with mock args but the returned value is null. I would like to avoid loading the entityManager.

Specification<MyClass> nullSpecification = Specification.where(null);
Specification<MyClass> nullSpecification2 = Specification.where(null);
assertEquals(nullSpecification, nullSpecification2);

I expected assertEquals(nullSpecification, nullSpecification2) to return true but the actual value is false. How can I compare JPA Specification ?


Solution

  • I see the following options.

    1. Bite the bullet and create an integration test, i.e. create an EntityManager and run queries against an in memory database or Testcontainers.

    2. Inspect the internals of the generated Predicate by passing in carefully configured mocks and then using type checking, reflection and knowledge of internals of your JPA provider to assert that you'll get the right predicate.

    The problem with the 2nd approach is that it is very brittle and is likely to break although the Specification is actually fine. I therefore would go with option 1 although I'd prefer a unit test as well.