Spring boot - unit testing Spring Data JPA repositories

user10235054 :

I have a repository (say, MovieRepository) created with the help of Spring Data.

public interface MovieRepository extends JpaRepository<Movie, Short> {}  

Let's say i want to unit test one of the methods provided by JpaRepository interface for exemple getOne(short id), is that making sense ? as i'm usually not writing any implementation code myself.

And what about if i write a method with query myself, for exemple:

@Query("SELECT m " +
            "FROM Movie m inner join  MovieGenre mg ON m.id = mg.movie.id " +
            "WHERE mg.genre.id = (SELECT mg2.genre.id FROM MovieGenre mg2 WHERE mg2.movie.id = ?1 AND mg2.movie.id <> mg.movie.id AND mg.genre.id = mg2.genre.id) " +
            "GROUP BY mg.movie.id " +
            "ORDER BY count(m) DESC")
Page<Movie> findRelatedMoviesToMovieById(@Param("id") short id, Pageable pageable);  

Should i test this method ?

Ervin Szilagyi :

There is no reason to write a unit test for a repository, since you are not writing any implementation code yourself. It is more advisable to write integration tests if you want to test your queries. These are done by using an in-memory database and the tests should be run within the Spring container. Spring-Boot has a lot of support for doing integration testing:

  • the tests should be run with @RunWith(SpringRunner.class) which brings up the Spring container;
  • @DataJpaTest - these should be used in combination with SpringRunner.class in order to run an in-memory database;

Example:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MovieRepositoryTests {

   @Autowired
   private MovieRepository myRepository;

   @Test
   public void findRelatedMoviesToMovieByIdTest() {
       ...
       Page<Movie> movies= myRepository.findRelatedMoviesToMovieByIdTest(1, new PageRequest(1, 10));
       ...
   }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=95797&siteId=1