原文: http://zetcode.com/springboot/testentitymanager/

Spring Boot TestEntityManager教程展示了如何在 JPA 测试中使用TestEntityManagerTestEntityManager提供了EntityManager方法的子集,可用于测试以及用于常见测试任务(例如persistfind)的辅助方法。

Spring 是用于创建企业应用的流行 Java 应用框架。 Spring Boot 是 Spring 框架的演进,可帮助您轻松创建独立的,生产级的基于 Spring 的应用。

TestEntityManager

TestEntityManager允许在测试中使用EntityManager。 Spring RepositoryEntityManager的抽象; 它使开发者免受 JPA 底层细节的困扰,并带来了许多便捷的方法。 但是 Spring 允许在应用代码和测试中需要时使用EntityManager

在我们的测试中,我们可以从应用中注入DataSource@JdbcTemplate@EntityManager或任何 Spring Data 存储库。

Spring TestEntityManager示例

以下应用使用TestEntityManager以测试方法保存了一些城市实体。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. Application.java
  8. MyRunner.java
  9. ├───model
  10. City.java
  11. └───repository
  12. CityRepository.java
  13. └───resources
  14. └───test
  15. └───java
  16. └───com
  17. └───zetcode
  18. └───repository
  19. CityRepositoryTest.java

这是项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>springboottestentitymanager</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. </properties>
  16. <parent>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-parent</artifactId>
  19. <version>2.1.1.RELEASE</version>
  20. </parent>
  21. <dependencies>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-data-jpa</artifactId>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-test</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. <dependency>
  32. <groupId>com.h2database</groupId>
  33. <artifactId>h2</artifactId>
  34. <scope>runtime</scope>
  35. </dependency>
  36. </dependencies>
  37. <build>
  38. <plugins>
  39. <plugin>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-maven-plugin</artifactId>
  42. </plugin>
  43. </plugins>
  44. </build>
  45. </project>

Maven POM 文件包含 Spring Data JPA,测试和 H2 数据库的依赖项。

com/zetcode/model/City.java

  1. package com.zetcode.model;
  2. import java.util.Objects;
  3. import javax.persistence.Entity;
  4. import javax.persistence.GeneratedValue;
  5. import javax.persistence.GenerationType;
  6. import javax.persistence.Id;
  7. import javax.persistence.Table;
  8. @Entity
  9. @Table(name = "cities")
  10. public class City {
  11. @Id
  12. @GeneratedValue(strategy = GenerationType.AUTO)
  13. private Long id;
  14. private String name;
  15. private int population;
  16. public City() {
  17. }
  18. public City(String name, int population) {
  19. this.name = name;
  20. this.population = population;
  21. }
  22. public Long getId() {
  23. return id;
  24. }
  25. public void setId(Long id) {
  26. this.id = id;
  27. }
  28. public String getName() {
  29. return name;
  30. }
  31. public void setName(String name) {
  32. this.name = name;
  33. }
  34. public int getPopulation() {
  35. return population;
  36. }
  37. public void setPopulation(int population) {
  38. this.population = population;
  39. }
  40. @Override
  41. public int hashCode() {
  42. int hash = 7;
  43. hash = 79 * hash + Objects.hashCode(this.id);
  44. hash = 79 * hash + Objects.hashCode(this.name);
  45. hash = 79 * hash + this.population;
  46. return hash;
  47. }
  48. @Override
  49. public boolean equals(Object obj) {
  50. if (this == obj) {
  51. return true;
  52. }
  53. if (obj == null) {
  54. return false;
  55. }
  56. if (getClass() != obj.getClass()) {
  57. return false;
  58. }
  59. final City other = (City) obj;
  60. if (this.population != other.population) {
  61. return false;
  62. }
  63. if (!Objects.equals(this.name, other.name)) {
  64. return false;
  65. }
  66. return Objects.equals(this.id, other.id);
  67. }
  68. @Override
  69. public String toString() {
  70. var builder = new StringBuilder();
  71. builder.append("City{id=").append(id).append(", name=")
  72. .append(name).append(", population=")
  73. .append(population).append("}");
  74. return builder.toString();
  75. }
  76. }

这是City实体。

com/zetcode/repository/CityRepository.java

  1. package com.zetcode.repository;
  2. import com.zetcode.model.City;
  3. import org.springframework.data.repository.CrudRepository;
  4. import org.springframework.stereotype.Repository;
  5. import java.util.List;
  6. @Repository
  7. public interface CityRepository extends CrudRepository<City, Long> {
  8. List<City> findByName(String name);
  9. }

CityRepository包含自定义的findByName()方法。 Spring 检查方法的名称,并从其关键字派生查询。

com/zetcode/MyRunner.java

  1. package com.zetcode;
  2. import com.zetcode.model.City;
  3. import com.zetcode.repository.CityRepository;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.CommandLineRunner;
  8. import org.springframework.stereotype.Component;
  9. @Component
  10. public class MyRunner implements CommandLineRunner {
  11. private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);
  12. @Autowired
  13. private CityRepository cityRepository;
  14. @Override
  15. public void run(String... args) throws Exception {
  16. logger.info("Saving cities");
  17. cityRepository.save(new City("Bratislava", 432000));
  18. cityRepository.save(new City("Budapest", 1759000));
  19. cityRepository.save(new City("Prague", 1280000));
  20. cityRepository.save(new City("Warsaw", 1748000));
  21. logger.info("Retrieving cities");
  22. var cities = cityRepository.findAll();
  23. cities.forEach(city -> logger.info("{}", city));
  24. }
  25. }

MyRunner中,我们使用CityRepository保存和检索实体。 数据存储在内存中的 H2 数据库中。

注意:在Java企业应用中,定义与存储库一起使用的服务层是一个好习惯。 为简单起见,我们跳过服务层。

com/zetcode/Application.java

  1. package com.zetcode;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class Application {
  6. public static void main(String[] args) {
  7. SpringApplication.run(Application.class, args);
  8. }
  9. }

Application设置 Spring Boot 应用。 @SpringBootApplication启用自动配置和组件扫描。

com/zetcode/repository/CityRepositoryTest.java

  1. package com.zetcode.repository;
  2. import com.zetcode.model.City;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
  7. import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import static org.assertj.core.api.Assertions.assertThat;
  10. import static org.junit.Assert.assertEquals;
  11. @RunWith(SpringRunner.class)
  12. @DataJpaTest
  13. public class CityRepositoryTest {
  14. @Autowired
  15. private TestEntityManager entityManager;
  16. @Autowired
  17. private CityRepository repository;
  18. @Test
  19. public void testFindByName() {
  20. entityManager.persist(new City("Bratislava", 432000));
  21. entityManager.persist(new City("Budapest", 1759000));
  22. entityManager.persist(new City("Prague", 1280000));
  23. entityManager.persist(new City("Warsaw", 1748000));
  24. var cities = repository.findByName("Bratislava");
  25. assertEquals(1, cities.size());
  26. assertThat(cities).extracting(City::getName).containsOnly("Bratislava");
  27. }
  28. }

CityRepositoryTest中,我们测试了自定义 JPA 方法。

  1. @Autowired
  2. private TestEntityManager entityManager;

我们注入TestEntityManager

  1. @RunWith(SpringRunner.class)
  2. @DataJpaTest
  3. public class CityRepositoryTest {

@DataJpaTest用于测试 JPA 信息库。 它与@RunWith(SpringRunner.class)结合使用。 注解会禁用完全自动配置,并且仅应用与 JPA 测试相关的配置。 默认情况下,用@DataJpaTest注解的测试使用嵌入式内存数据库。

  1. entityManager.persist(new City("Bratislava", 432000));
  2. entityManager.persist(new City("Budapest", 1759000));
  3. entityManager.persist(new City("Prague", 1280000));
  4. entityManager.persist(new City("Warsaw", 1748000));

我们用EntityManagerpersist()方法保存了四个城市。

  1. var cities = repository.findByName("Bratislava");
  2. assertEquals(1, cities.size());

我们测试findByName()方法返回一个城市。

  1. assertThat(cities).extracting(City::getName).containsOnly("Bratislava");

在这里,我们测试城市的名称。

  1. $ mvn spring-boot:test

我们运行测试。

在本教程中,我们在测试中使用了TestEntityManager

列出所有 Spring Boot 教程