Testing Those Specifications
Let's take a look at how to provide test coverage for JPA specifications.
Join the DZone community and get the full member experience.
Join For FreeIn 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.
Source Code
To see the complete source code, simply launch the following URL:
https://gitlab.com/johnjvester/jpa-spec
Have a really great day!
Opinions expressed by DZone contributors are their own.
Comments