Spring Boot + Spring Data JPA Repository Unit Test (2024) Example | CodeUsingJava






















Spring Boot + Spring Data JPA Repository Unit Test (2024) Example

Unit Testing plays an important role in the development of any enterprise application. Unit Testing includes the testing of a single method at a time and here we exclude all the other components.
Junit is a framework and one of the essential tool for testing which helps in performing the unit tests.
The flow of Junit can be described as follows:-
The Test Runner helps in performing all the test cases.
Spring Boot Maven junit flow dig
In our example, we have taken a sample example and used hyper SQL Database for the purpose of storage. We have applied some of the test cases and then checked the unit test cases using junit.

Project Structure

  • This will be the standard directory layout for maven project structure-
    Spring Boot Maven Project Structure
    We need to start by creating a Maven pom.xml(Project Object Model) file. The pom.xml file contains the project configuration details.
    	<?xml version="1.0" encoding="UTF-8"?>
    	<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    		xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    		<modelVersion>4.0.0</modelVersion>
    	
    		<groupId>com.codeusingjava</groupId>
    		<artifactId>SpringBootJunitTest</artifactId>
    		<version>0.0.1-SNAPSHOT</version>
    		<packaging>jar</packaging>
    	
    		<name>SpringJPAUnitTest</name>
    		<description>Demo project for Spring Boot JPA Unit Test</description>
    	
    		<parent>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-parent</artifactId>
    			<version>1.4.2.RELEASE</version>
    			<relativePath /> <!-- lookup parent from repository -->
    		</parent>
    	
    		<properties>
    			<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    			<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    			<java.version>1.8</java.version>
    		</properties>
    	
    		<dependencies>
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter</artifactId>
    			</dependency>
    	
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter-data-jpa</artifactId>
    			</dependency>
    	
    			<dependency>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-starter-test</artifactId>
    				<scope>test</scope>
    			</dependency>
    	
    			<dependency>
    				<groupId>org.hsqldb</groupId>
    				<artifactId>hsqldb</artifactId>
    				<scope>test</scope>
    			</dependency>
    		</dependencies>
    	
    		<build>
    			<plugins>
    				<plugin>
    					<groupId>org.springframework.boot</groupId>
    					<artifactId>spring-boot-maven-plugin</artifactId>
    				</plugin>
    			</plugins>
    		</build>
    	
    	
    	</project>
    	
    
    Creating the model class named Player with all the getters, setters, constructors and ToString method in it.
    	package com.codeusingjava.model;
    
    	import java.io.Serializable;
    	
    	import javax.persistence.Column;
    	import javax.persistence.Entity;
    	import javax.persistence.GeneratedValue;
    	import javax.persistence.GenerationType;
    	import javax.persistence.Id;
    	import javax.persistence.Table;
    	
    	@Entity
    	@Table(name = "player")
    	public class Player implements Serializable {
    	
    		private static final long serialVersionUID = -3009157732242241606L;
    		@Id
    		@GeneratedValue(strategy = GenerationType.AUTO)
    		private long id;
    	
    		@Column(name = "name")
    		private String name;
    	
    		@Column(name = "country")
    		private String country;
    	
    		public Player(long id, String name, String country) {
    			super();
    			this.id = id;
    			this.name = name;
    			this.country = country;
    		}
    		
    		public Player( String name, String country) {
    			
    			this.name = name;
    			this.country = country;
    		}
    	
    		public Player() {
    			super();
    			// TODO Auto-generated constructor stub
    		}
    	
    		public long getId() {
    			return id;
    		}
    	
    		public void setId(long id) {
    			this.id = id;
    		}
    	
    		public String getName() {
    			return name;
    		}
    	
    		public void setName(String name) {
    			this.name = name;
    		}
    	
    		public String getCountry() {
    			return country;
    		}
    	
    		public void setCountry(String country) {
    			this.country = country;
    		}
    	
    		public static long getSerialversionuid() {
    			return serialVersionUID;
    		}
    	
    		
    	}
    	
    

    Creating the repository class for the Player.
    	package com.codeusingjava.repository;
    
    	import java.util.List;
    	
    	import org.springframework.data.repository.CrudRepository;
    	
    	import com.codeusingjava.model.Player;
    	
    	public interface PlayerRepository extends CrudRepository<Player, Long> {
    		List<Player> findByCountry(String country);
    	}
    	
    
    
    Following is the class where unit tests are to be checked:
    With the help of @Test annotation, Junit knows that the following class is to be checked as a Test case.
    Using @DataJpaTest annotation helps in auto configuration of the beans in our repositories.
    The assertThat method helps in checking whether the values provided in the method gets matched with that of expected value.
    	package com.codeusingjava;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
    import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import com.codeusingjava.model.Player;
    import com.codeusingjava.repository.PlayerRepository;
    
    @RunWith(SpringRunner.class)
    @DataJpaTest
    public class JPAUnitTests {
    
    	@Autowired
    	private TestEntityManager entityManager;
    
    	@Autowired
    	PlayerRepository repository;
    
    	@Test
    	public void find_no_players_if_repo_is_empty() {
    		Iterable<Player> players = repository.findAll();
    
    		assertThat(players).isEmpty();
    	}
    
    	@Test
    	public void save_a_player() {
    		Player player = repository.save(new Player("Saina Nehwal", "India"));
    
    		assertThat(player).hasFieldOrPropertyWithValue("name", "Saina Nehwal");
    		
    	
    	}
    
    	@Test
    	public void delete_all_player() {
    		entityManager.persist(new Player("Saina Nehwal", "India"));
    		entityManager.persist(new Player("Sachin Tendulkar", "India"));
    
    		repository.deleteAll();
    
    		assertThat(repository.findAll()).isEmpty();
    	}
    
    	@Test
    	public void find_all_players() {
    		Player player1 = new Player("Saina Nehwal", "India");
    		entityManager.persist(player1);
    
    		Player player2 = new Player("Sachin Tendulkar", "India");
    		entityManager.persist(player2);
    
    		Player player3 = new Player("Krishna Poonia", "India");
    		entityManager.persist(player3);
    
    		Iterable<Player> players = repository.findAll();
    
    		assertThat(players).hasSize(3).contains(player1, player2, player3);
    	}
    
    	@Test
    	public void find_player_by_id() {
    		Player player1 = new Player("Sachin Tendulkar", "India");
    		entityManager.persist(player1);
    
    		Player player2 = new Player("Saina Nehwal", "India");
    		entityManager.persist(player2);
    
    		Player getPlayer = repository.findOne(player2.getId());
    
    		assertThat(getPlayer).isEqualTo(player2);
    	}
    
    }
    
    

    Following is the class which is created by default inside the test package:
    The contextLoads method helps in testing whether all the spring context are properly loaded or not.
    	package com.codeusingjava;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class JpaUnitTestSpringApplicationTests {
    
    	@Test
    	public void contextLoads() {
    	}
    
    }
    
    
If we now run the application by Run as -> Junit Test, we get the output as follows:-
In case any exception is thrown then failure is shown in that particular test case.
Spring Boot Maven junit test

Downloads-

Spring Boot + Spring Data JPA Repository Unit Test Example