Spring Boot @DataJpaTest示例

x33g5p2x  于2022-10-13 转载在 Spring  
字(3.8k)|赞(0)|评价(0)|浏览(686)

在本教程中,我们将学习如何使用Spring引导提供的@DataJpaTest注解来测试Repository层组件。
我们使用Spring boot starter测试依赖项为Repository层组件编写JUnit测试:

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

@DataJpaTest注解概述

SpringBoot提供了@DataJpaTest注解来测试持久层组件,这些组件将自动配置内存嵌入式数据库以进行测试。
@DataJpaTest注解不会将其他Springbean(@Components、@Controller、@Service和注解bean)加载到ApplicationContext中。默认情况下,它扫描@Entity类并配置用@Repository注解注解的Spring Data JPA存储库。
默认情况下,用@DataJpaTest注解的测试是事务性的,并在每个测试结束时回滚。
Spring引导提供的@DataJpaTest注解不仅用于测试Spring Data JPA存储库,还支持测试JPA相关组件。
例如:

@DataJpaTestSpring Boot示例

创建Spring Boot应用程序

使用spring initialize创建Spring Boot项目并添加以下依赖项:

  • Spring Data JPA
  • Lombok(Lombok)
  • H2 Driver

将Spring引导项目生成为zip文件,将其解压缩并导入IntelliJIDEA。
确保将以下依赖项添加到pom中。xml文件:

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

创建JPA实体

接下来,让我们创建一个学生JPA实体:

package net.javaguides.spirngboot.entity;

import lombok.*;

import javax.persistence.*;

@Setter
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "students")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;
    private String email;
}

创建Spring数据JPA存储库

让我们创建扩展JpaRepository界面的StudentRepository:

package net.javaguides.spirngboot.repository;

import net.javaguides.spirngboot.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {
}

使用H2数据库进行数据访问或存储库层的JUnit测试

让我们创建StudentRepositoryTests类并向其添加以下内容:

package net.javaguides.spirngboot.repository;

import net.javaguides.spirngboot.AbstractContainerBaseTest;
import net.javaguides.spirngboot.entity.Student;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import static org.junit.jupiter.api.Assertions.*;

@DataJpaTest
class StudentRepositoryTest {

    @Autowired
    private StudentRepository studentRepository;

    // JUnit for save student operation - BDD style
    @Test
    public void givenStudentObject_whenSave_thenReturnSavedStudent(){

        // given - setup or precondition
        Student student = Student.builder().firstName("Ramesh")
                .lastName("fadatare").email("ramesh@gmail.com").build();

        // when - action or the testing
        Student savedStudent = studentRepository.save(student);

        // then - very output
        Assertions.assertNotNull(savedStudent);
        Assertions.assertNotNull(savedStudent.getId());

    }

    // JUnit for findById student operation - BDD style
    @Test
    public void givenStudentId_whenfindbyId_thenReturnSavedStudent(){

        // given - setup or precondition
        Student student = Student.builder().firstName("Ramesh")
                .lastName("fadatare").email("ramesh@gmail.com").build();
        Student savedStudent = studentRepository.save(student);

        // when - action or the testing
        Student studentDB = studentRepository.findById(student.getId()).get();

        // then - very output
        Assertions.assertNotNull(studentDB);
    }

}

SpringBoot提供了@DataJpaTest注解来测试持久层组件,这些组件将自动配置内存嵌入式数据库以进行测试。在本例中,我们使用H2内存数据库进行测试。

运行JUnit测试

结论

在本教程中,我们学习了如何使用Spring引导提供的@DataJpaTest注解来测试Repository层组件。

相关文章