DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Testing Those Specifications

Testing Those Specifications

Let's take a look at how to provide test coverage for JPA specifications.

John Vester user avatar by
John Vester
CORE ·
Apr. 16, 19 · Tutorial
Like (2)
Save
Tweet
Share
111.28K Views

Join the DZone community and get the full member experience.

Join For Free

In my "Specifications to the Rescue" article, I talked about using Spring Data JPA Specifications (org.springframework.data.jpa.domain.Specification) to provide some easy filtering for a RESTful API.  

As a fan of including the unit and integration tests as part of application development — which is the subject of a future article in my backlog — I wanted to step through providing the necessary tests to validate and (code) cover the specifications that I introduced last month.

I have also updated my GitLab repository, for those who want to follow along.

Testing the Specifications

Specifications are a manner in which a subset of data can be returned, based upon a given need.  The JPARepository ( org.springframework.data.jpa.repository.JpaRepository ) is the interface that allows the specifications to be implemented. As a result, validating the functionality behind a specification will need to utilize a repository and some form of data.  

Creating the Tests

The base Spring-Boot project that I created for the original article, included a stub test class, called  JpaSpecApplicationTests.java  and is located in the com.gitlab.johnjvester.jpaspec  test package.

I have modified the class as follows, which includes injecting the classes that will be needed for the test:

@RunWith(SpringRunner.class)
@SpringBootTest(properties="spring.main.banner-mode=off")
@Transactional
public class JpaSpecApplicationTests {
    @Autowired
    private ClassRepository classRepository;

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private MemberSpecification memberSpecification;  
}


Setting Up the Data

While the jpa-spec project automatically loads data into an in-memory H2 database, most projects will not employ such a technique. Rather than build another in-memory database, I decided to new-up some objects in the test class itself — to provide some test data for validation:

@Before
public void init() {
    memberRepository.deleteAll();
    classRepository.deleteAll();

    Class classWaterPolo = new Class();
    classWaterPolo.setName("Water Polo");
    classRepository.save(classWaterPolo);

    Class classSwimming = new Class();
    classSwimming.setName("Swimming");
    classRepository.save(classSwimming);

    Class classLifting = new Class();
    classLifting.setName("Lifting");
    classRepository.save(classLifting);

    Class classPilates = new Class();
    classPilates.setName("Pilates");
    classRepository.save(classPilates);

    Class classZumba = new Class();
    classZumba.setName("Zumba");
    classRepository.save(classZumba);

    Set<Class> gregSet = new HashSet<>();
    gregSet.add(classWaterPolo);
    gregSet.add(classLifting);

    Member memberGreg = new Member();
    memberGreg.setActive(true);
    memberGreg.setFirstName("Greg");
    memberGreg.setLastName("Brady");
    memberGreg.setInterests("I love to cycle and swim");
    memberGreg.setZipCode("90210");
    memberGreg.setClasses(gregSet);
    memberRepository.save(memberGreg);

    Set<Class> marshaSet = new HashSet<>();
    marshaSet.add(classSwimming);
    marshaSet.add(classZumba);

    Member memberMarsha = new Member();
    memberMarsha.setActive(true);
    memberMarsha.setFirstName("Marsha");
    memberMarsha.setLastName("Brady");
    memberMarsha.setInterests("I love to do zumba and pilates");
    memberMarsha.setZipCode("90211");
    memberMarsha.setClasses(marshaSet);
    memberRepository.save(memberMarsha);

    Set<Class> aliceSet = new HashSet<>();
    aliceSet.add(classSwimming);

    Member memberAlice = new Member();
    memberAlice.setActive(false);
    memberAlice.setFirstName("Alice");
    memberAlice.setLastName("Nelson");
    memberAlice.setInterests("I used to love that belt machine-y thing");
    memberAlice.setZipCode("90201");
    memberAlice.setClasses(aliceSet);
    memberRepository.save(memberAlice);
}


Using this approach, everything related to the test is in the class file itself — which limits the amount of time that is required to locate information related to the test setup.  Of course, depending on the situation, this may not be an ideal approach.

Creating the Tests

With the necessary data, repositories, and specifications in place, we can add our first test. The first test will be to filter the Member  list to include only the active members. Looking at the data, Greg Brady and Marsha Brady are active members, while (the late) Alice Nelson is no longer active.

The following test will establish a FilterRequest, set the active  attribute to true, and execute the built-in findAll() method, while including the  getFilter() method, which will include the filter  (FilterRequest).

@Test
public void testMembersActive() {
    FilterRequest filter = new FilterRequest();
    filter.setActive(true);

    List<Member> memberList = memberRepository.findAll(memberSpecification.getFilter(filter));

    assertEquals(2, memberList.size());
}


The memberRepository will utilize the data provided in the init() method and the assertEquals() method will validate that the memberList.size() is equal to 2  (two) members.

Using this same pattern, tests can be added to validate the zip code filter functionality, the search string functionality, and a test that combines all three searches into one:

@Test
public void testMembersInZip902() {
    FilterRequest filter = new FilterRequest();
    filter.setZipFilter("902");

    List<Member> memberList = memberRepository.findAll(memberSpecification.getFilter(filter));

    assertEquals(3, memberList.size());
}

@Test
public void testMembersWithSwimClassOrInterest() {
    String searchString = "sWIM";

    List<Member> memberList = memberRepository.findAll(Specification.where(memberSpecification.hasString(searchString)
            .or(memberSpecification.hasClasses(searchString))));

    assertEquals(3, memberList.size());
}

@Test
public void testMembersActiveInZip902WithSwimClassOrInterest() {
    FilterRequest filter = new FilterRequest();
    filter.setActive(true);
    filter.setZipFilter("902");
    String searchString = "sWIM";

    List<Member> memberList = memberRepository.findAll(Specification.where(memberSpecification.hasString(searchString)
            .or(memberSpecification.hasClasses(searchString)))
            .and(memberSpecification.getFilter(filter)));

    assertEquals(2, memberList.size());
}


Running the Tests

Most development clients provide the ability to run unit/integration tests right from the interface. While it is possible to do that, we can also use Maven to run the tests as well, using the following command:mvn test .

This will return the following information:

[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.390 s
[INFO] Finished at: 2019-04-13T12:50:22-04:00
[INFO] Final Memory: 23M/331M
[INFO] ------------------------------------------------------------------------


From a code-coverage perspective, these four simple unit tests provide the following coverage for the BaseSpecification and MemberSpecification classes.

Image title

Source Code

To see the complete source code, simply launch the following URL:

https://gitlab.com/johnjvester/jpa-spec

Have a really great day!

unit test

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • DevOps Roadmap for 2022
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • The 31 Flavors of Data Lineage and Why Vanilla Doesn’t Cut It
  • Best Practices for Writing Clean and Maintainable Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: