I am learning how to create unit tests for my application and I don't know how to test custom query in repository.
I have the following UserRepository where there is a custom query that returns groups that contain specific User IDs so that each user gets the groups they created.
@Repository
public interface UserRepository extends JpaRepositry<User, Long>{
@Query("select g from Group g where g.user.id = ?1")
Page<Group> findGroupByUserId(Long Id, Pageable pageable);
}
And Im using this query like this:
public Page<Group> findGroupByUserId(Long Id, Pageable pageable){
return userRepository.findGroupByUserId(Id, pageable);
}
So my question is:
What should I test when using pageable like this? If there are specific groups with user id or just if there is the right number of groups?
Can somebody quide me on how to create this test when using pageable?
CodePudding user response:
What should I test when using pageable like this?
- Does your SQL statement actually execute.
- Does it select the values you want.
- Does it not select the values you don't want.
For point 2 and three it is important to think about the possible values you might put in as a parameter.
- a valid user id.
null
To perform these test you may create 3 groups, 2 users, and assign user 1 to groups 1 and 2 and user 2 to groups 2 and 3 and then query for one user and check that you get the correct result back.
Repeat by query for null
if that is possible in your application.
You check for the correct result by looking for the ids of the groups.
You might want to go beyond that:
- How does it perform with large amount of data
- Can you trigger errors with huge positive or negative values for
Id
or thePageable
- ...
But these are specialized concerns and I'll ignore them for now since you are just starting with testing.
Things you probably don't need to test:
- Are the
Group
objects instantiated correctly? Your JPA implementation does that for you. You might want to have a separate test of persisting and loading aGroup
instance to test your mapping, but don't mix that with the test we are talking about right now. - That the
Page
is constructed correctly. - That transactions are handled correctly.
- That connections are opened and closed correctly.
- ....
All that stuff is done by libraries and they are pretty well tested. That doesn't mean they don't have bugs, but hunting for those by adding tests for your custom query doesn't sound like a good investment.
Can somebody guide me on how to create this test when using pageable? I'm not sure how
Pageable
is a problem here, since I wouldn't eve test for multiple pages. Just create a page usingPageable.ofSize(10)
and be done with it.