Spring Boot TestEntityManager 教程展示了如何在 JPA 测试中使用 TestEntityManager。 TestEntityManager 提供了 EntityManager 方法的子集,可用于测试以及用于常见测试任务(例如 persist 或 find)的辅助方法。
Spring 是用于创建企业应用的流行 Java 应用框架。 Spring Boot 是 Spring 框架的演进,可帮助您轻松创建独立的,生产级的基于 Spring 的应用。
TestEntityManager
TestEntityManager
允许在测试中使用EntityManager
。 Spring Repository
是EntityManager
的抽象; 它使开发人员免受 JPA 底层细节的困扰,并带来了许多便捷的方法。 但是 Spring 允许在应用代码和测试中需要时使用EntityManager
。
在我们的测试中,我们可以从应用中注入 DataSource,@ JdbcTemplate,@ EntityManager 或任何 Spring Data 存储库。
Spring TestEntityManager
示例
以下应用使用TestEntityManager
以测试方法保存了一些城市实体。
这是项目结构。
pom.xml
Maven POM 文件包含 Spring Data JPA,测试和 H2 数据库的依赖项。
com/zetcode/model/City.java
这是City
实体。
com/zetcode/repository/CityRepository.java
CityRepository
包含自定义的findByName()
方法。 Spring 检查方法的名称,并从其关键字派生查询。
com/zetcode/MyRunner.java
在MyRunner
中,我们使用CityRepository
保存和检索实体。 数据存储在内存中的 H2 数据库中。
Note: In Java enterprise applications it is a good practice to define a service layer that works with repositories. For simplicity reasons, we skip the service layer.
com/zetcode/Application.java
Application
设置 Spring Boot 应用。 @SpringBootApplication
启用自动配置和组件扫描。
com/zetcode/repository/CityRepositoryTest.java
在CityRepositoryTest
中,我们测试了自定义 JPA 方法。
我们注入TestEntityManager
。
@DataJpaTest
用于测试 JPA 信息库。 它与@RunWith(SpringRunner.class)结合使用。 注解会禁用完全自动配置,并且仅应用与 JPA 测试相关的配置。 默认情况下,用@DataJpaTest 注解的测试使用嵌入式内存数据库。
我们用EntityManager's
persist()
方法保存了四个城市。
我们测试findByName()
方法返回一个城市。
在这里,我们测试城市的名称。
我们运行测试。
在本教程中,我们在测试中使用了TestEntityManager
。