Spring Boot TestEntityManager
最后修改于 2023 年 7 月 29 日
在本文中,我们将展示如何在 JPA 测试中使用 TestEntityManager。 TestEntityManager 提供了 EntityManager 方法的一个子集,这些方法对于测试很有用,以及用于常见测试任务(如 persist 或 find)的辅助方法。
Spring 是一个流行的 Java 应用程序框架,用于创建企业应用程序。Spring Boot 是 Spring 框架的演进,它有助于以最小的 effort 创建基于 Spring 的独立、生产级应用程序。
TestEntityManager
TestEntityManager
允许在测试中使用 EntityManager
。 Spring Repository
是对 EntityManager
的抽象;它使开发人员免受 JPA 底层细节的困扰,并带来了许多方便的方法。 但是 Spring 允许在应用程序代码和测试中根据需要使用 EntityManager
。
在我们的测试中,我们可以从应用程序中注入 DataSource、@JdbcTemplate、@EntityManager 或任何 Spring Data 存储库。
Spring TestEntityManager 示例
以下应用程序使用 TestEntityManager
在测试方法中保存几个城市实体。
build.gradle ... src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ │ MyRunner.java │ │ ├───model │ │ │ City.java │ │ └───repository │ │ CityRepository.java │ └───resources └───test └───java └───com └───zetcode └───repository CityRepositoryTest.java
这是项目结构。
plugins { id 'org.springframework.boot' version '3.1.1' id 'io.spring.dependency-management' version '1.1.0' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' testImplementation 'org.springframework.boot:spring-boot-starter-test' runtimeOnly 'com.h2database:h2' } test { useJUnitPlatform() }
Gradle 构建文件包含 Spring Data JPA、测试和 H2 数据库的依赖项。
package com.zetcode.model; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.Table; import java.util.Objects; @Entity @Table(name = "cities") public class City { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private int population; public City() { } public City(String name, int population) { this.name = name; this.population = population; } 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 int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public int hashCode() { int hash = 7; hash = 79 * hash + Objects.hashCode(this.id); hash = 79 * hash + Objects.hashCode(this.name); hash = 79 * hash + this.population; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final City other = (City) obj; if (this.population != other.population) { return false; } if (!Objects.equals(this.name, other.name)) { return false; } return Objects.equals(this.id, other.id); } @Override public String toString() { var builder = new StringBuilder(); builder.append("City{id=").append(id).append(", name=") .append(name).append(", population=") .append(population).append("}"); return builder.toString(); } }
这是 City
实体。
package com.zetcode.repository; import com.zetcode.model.City; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface CityRepository extends CrudRepository<City, Long> { List<City> findByName(String name); }
CityRepository
包含自定义的 findByName
方法。 Spring 检查方法的名称,并从其关键字派生查询。
package com.zetcode; import com.zetcode.model.City; import com.zetcode.repository.CityRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(MyRunner.class); private final CityRepository cityRepository; @Autowired public MyRunner(CityRepository cityRepository) { this.cityRepository = cityRepository; } @Override public void run(String... args) throws Exception { logger.info("Saving cities"); cityRepository.save(new City("Bratislava", 432000)); cityRepository.save(new City("Budapest", 1759000)); cityRepository.save(new City("Prague", 1280000)); cityRepository.save(new City("Warsaw", 1748000)); logger.info("Retrieving cities"); var cities = cityRepository.findAll(); cities.forEach(city -> logger.info("{}", city)); } }
在 MyRunner
中,我们使用 CityRepository
来保存和检索实体。 数据存储在内存中的 H2 数据库中。
package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Application
设置了 Spring Boot 应用程序。@SpringBootApplication
启用了自动配置和组件扫描。
package com.zetcode.repository; import com.zetcode.model.City; import org.junit.jupiter.api.Test; 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 static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @DataJpaTest public class CityRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private CityRepository repository; @Test public void testFindByName() { entityManager.persist(new City("Bratislava", 432000)); entityManager.persist(new City("Budapest", 1759000)); entityManager.persist(new City("Prague", 1280000)); entityManager.persist(new City("Warsaw", 1748000)); var cities = repository.findByName("Bratislava"); assertEquals(1, cities.size()); assertThat(cities).extracting(City::getName).containsOnly("Bratislava"); } }
在 CityRepositoryTest
中,我们测试自定义 JPA 方法。
@Autowired private TestEntityManager entityManager;
我们注入 TestEntityManager
。
@DataJpaTest public class CityRepositoryTest {
@DataJpaTest
用于测试 JPA 存储库。 该注解禁用完全自动配置,仅应用与 JPA 测试相关的配置。 默认情况下,使用 @DataJpaTest 注释的测试使用嵌入式内存数据库。
entityManager.persist(new City("Bratislava", 432000)); entityManager.persist(new City("Budapest", 1759000)); entityManager.persist(new City("Prague", 1280000)); entityManager.persist(new City("Warsaw", 1748000));
我们使用 EntityManager
的 persist
方法保存四个城市。
var cities = repository.findByName("Bratislava"); assertEquals(1, cities.size());
我们测试 findByName
方法是否返回一个城市。
assertThat(cities).extracting(City::getName).containsOnly("Bratislava");
在这里,我们测试城市名称。
$ ./gradlew test
我们运行测试。
在本文中,我们在测试中使用了 TestEntityManager
。