Home > Software design >  How to test custom query in repository?
How to test custom query in repository?

Time:10-03

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:

  1. 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?

  2. 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?

  1. Does your SQL statement actually execute.
  2. Does it select the values you want.
  3. 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.

  1. a valid user id.
  2. 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:

  1. How does it perform with large amount of data
  2. Can you trigger errors with huge positive or negative values for Id or the Pageable
  3. ...

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:

  1. 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 a Group instance to test your mapping, but don't mix that with the test we are talking about right now.
  2. That the Page is constructed correctly.
  3. That transactions are handled correctly.
  4. That connections are opened and closed correctly.
  5. ....

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 using Pageable.ofSize(10) and be done with it.

  • Related