How to Test Spring Data Repository

Usually we do not need to write tests for the functionalities provided by the framework, but we can do so when certain functionalities we use from the framework is not so clearcut. An example is when we are using the custom query creation by function method in Spring Data. Using back the example from my previous post — Getting started Spring Boot Application, we have the following query by function name — findAllByTopic_TopicId.

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findAllByTopic_TopicId(Long topicId);
}

If we are not that familiar with the function name conventions, it will be good to just write a test to ensure it works as intended.

To write a new test class for the repository, we need to use the @DataJpaTest annotation.

@ExtendWith(SpringExtension.class)
@DataJpaTest
public class PostRepositoryTest {}

This annotation will help setup the environment you need to test the repository, like performing entity scan, so that you can use dependency injection, as well as turning on logging. With this annotation, the tests in the class will be transactional and rolled back at the end of each test, and it will use the embedded in-memory database. Do include h2 database in the dependencies of your gradle or maven file.

testImplementation 'com.h2database:h2:2.1.214'

Then we autowire a TestEntityManager and the repository we want to test into the class.

@Autowired
private TestEntityManager entityManager;

@Autowired
private PostRepositoryTest repository;

The TestEntityManager is a subset of EntityManager, with methods useful for tests. We’ll use it to insert data to our in memory database.

The context in our example is such that a Topic can have multiple Posts, joined by the foreign key TopicId. And our method is retrieving all the posts based on the TopicId.

We are using the GivenWhenThen style to write our test. Our precondition is to first create the data — a Topic and 2 Posts, then we persist and flush to save it the the database.

The action — denoted by the when, is where we execute the method that we want to test.

Lastly, the then section is where we specify the expected outcome with our assertion statements.

@Test
public void givenTopicHasPosts_whenFindAllByTopic_TopicId_thenReturnTopics(){
//given
Topic topic = new Topic("First Topic");
entityManager.persist(topic);
entityManager.flush();
Post post1 = new Post("First Post", topic);
Post post2 = new Post("Second Post", topic);
entityManager.persist(post1);
entityManager.persist(post2);
entityManager.flush();

//when
List<Post> postList = postRepository.findAllByTopic_TopicId(topic.getTopicId());

//then
assertThat(postList.size(), is(2));
assertThat(postList, containsInAnyOrder(post1, post2));
}

Lastly, we can add the following settings to the application.properties in the src/test/resources folder to show and format the sql that are generated by the framework in our log.

spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true

A working copy of the code is available on my github repository.

This article is originally published on https://thecodinganalyst.github.io/knowledgebase/how-to-test-spring-data-repository/.


How to Test Spring Data Repository was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Dennis

Usually we do not need to write tests for the functionalities provided by the framework, but we can do so when certain functionalities we use from the framework is not so clearcut. An example is when we are using the custom query creation by function method in Spring Data. Using back the example from my previous post — Getting started Spring Boot Application, we have the following query by function name — findAllByTopic_TopicId.

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
List<Post> findAllByTopic_TopicId(Long topicId);
}

If we are not that familiar with the function name conventions, it will be good to just write a test to ensure it works as intended.

To write a new test class for the repository, we need to use the @DataJpaTest annotation.

@ExtendWith(SpringExtension.class)
@DataJpaTest
public class PostRepositoryTest {}

This annotation will help setup the environment you need to test the repository, like performing entity scan, so that you can use dependency injection, as well as turning on logging. With this annotation, the tests in the class will be transactional and rolled back at the end of each test, and it will use the embedded in-memory database. Do include h2 database in the dependencies of your gradle or maven file.

testImplementation 'com.h2database:h2:2.1.214'

Then we autowire a TestEntityManager and the repository we want to test into the class.

@Autowired
private TestEntityManager entityManager;

@Autowired
private PostRepositoryTest repository;

The TestEntityManager is a subset of EntityManager, with methods useful for tests. We’ll use it to insert data to our in memory database.

The context in our example is such that a Topic can have multiple Posts, joined by the foreign key TopicId. And our method is retrieving all the posts based on the TopicId.

We are using the GivenWhenThen style to write our test. Our precondition is to first create the data — a Topic and 2 Posts, then we persist and flush to save it the the database.

The action — denoted by the when, is where we execute the method that we want to test.

Lastly, the then section is where we specify the expected outcome with our assertion statements.

@Test
public void givenTopicHasPosts_whenFindAllByTopic_TopicId_thenReturnTopics(){
//given
Topic topic = new Topic("First Topic");
entityManager.persist(topic);
entityManager.flush();
Post post1 = new Post("First Post", topic);
Post post2 = new Post("Second Post", topic);
entityManager.persist(post1);
entityManager.persist(post2);
entityManager.flush();

//when
List<Post> postList = postRepository.findAllByTopic_TopicId(topic.getTopicId());

//then
assertThat(postList.size(), is(2));
assertThat(postList, containsInAnyOrder(post1, post2));
}

Lastly, we can add the following settings to the application.properties in the src/test/resources folder to show and format the sql that are generated by the framework in our log.

spring.jpa.show-sql = true
spring.jpa.properties.hibernate.format_sql=true

A working copy of the code is available on my github repository.

This article is originally published on https://thecodinganalyst.github.io/knowledgebase/how-to-test-spring-data-repository/.


How to Test Spring Data Repository was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Dennis


Print Share Comment Cite Upload Translate Updates
APA

Dennis | Sciencx (2023-01-19T14:49:49+00:00) How to Test Spring Data Repository. Retrieved from https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/

MLA
" » How to Test Spring Data Repository." Dennis | Sciencx - Thursday January 19, 2023, https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/
HARVARD
Dennis | Sciencx Thursday January 19, 2023 » How to Test Spring Data Repository., viewed ,<https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/>
VANCOUVER
Dennis | Sciencx - » How to Test Spring Data Repository. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/
CHICAGO
" » How to Test Spring Data Repository." Dennis | Sciencx - Accessed . https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/
IEEE
" » How to Test Spring Data Repository." Dennis | Sciencx [Online]. Available: https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/. [Accessed: ]
rf:citation
» How to Test Spring Data Repository | Dennis | Sciencx | https://www.scien.cx/2023/01/19/how-to-test-spring-data-repository/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.