我有一个 Spring Boot 应用程序,从使用 SessionFactory 的旧式 Hibernate DAO 迁移到 Spring 的 JpaRepositories。
我面临的问题是,在单元测试中,我对旧的 Hibernate DAO 进行了一些测试,这些测试也加入了现在是 JpaRepository 的新表。以前,我只是 @Autowired 所有声明为测试 bean 的 Hibernate DAO 并执行我想要的任何操作。现在,我不能再这样做了,因为我无法将 JpaRepository 自动连接到这样的 Hibernate DAO 测试中。
更深入地说,我在 Hibernate 单元测试上有一个配置,它声明了如下存储库:
@Bean
public SomeDao someDao() {
SomeDao someDao = new HibernateSomeDao();
someDao.setSessionFactory(sessionFactory().getObject());
return someDao;
}
对于我的新 JpaRepositories 测试,我使用以下配置:
@DataJpaTest
@ContextConfiguration(initializers = TestContainersInitializer.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // use Testcontainers
现在,我需要做的是能够在为第一个用例(即 Hibernate DAO 测试)注释的类中自动装配 JpaRepository。对于上下文,我还使用 Testcontainers。我尝试过创建一个用 @DataJpaTest 注释的新配置类,并为新的 JpaRepository 创建一个 bean,然后我将其作为 Bean 导入到旧的测试类中,但这没有任何帮助。我认为你不能用 @DataJpaTest 注释 @TestConfiguration 类。
底线,我的问题是:如何为 JpaRepository 创建测试 bean?
我认为您正在寻找的是
@DataJpaTest
注释。此注释有助于 Spring Boot 为 JPA 存储库设置可测试的环境。
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@DataJpaTest
public class TestJpaConfiguration {
@Bean
public YourJpaRepository yourJpaRepository() {
// below you create an instance of your JpaRepository or mock it for
testing purpose
return Mockito.mock(YourJpaRepository.class);
}
}
现在使用
@SpringJUnitConfig(TestJpaConfiguration.class)
编写 DAO 测试。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(TestJpaConfiguration.class)
public class HibernateDaoTest {
@Autowired
private SomeDao someDao; // Autowire the DAO
@Autowired
private YourJpaRepository yourJpaRepository; // Autowire the JpaRepository
// Write your tests here
}
您可能还需要根据您的需要使用
@AutoConfigureTestDatabase
。
希望这有帮助。