我的项目正在使用Spring,Hibernate ant JUnit5。在进行所有测试之前,初始化DB的最佳方法是什么?
这是我厌倦的事情:
class DbCreatorService {
@Autowired
private Service1;
@Autowired
private Service2;
....
}
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
@Transactional
class MyTest {
@BeforeAll
static void initDatabase(@Autowired DbCreatorService dbCreatorService ) {
dbCreatorService.initDB()
}
}
当我在sessionFactory.getCurrentSession()
中某个地方呼叫initDB()
时,会得到:org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
。 sessionFactory
被注入@Autowired。
答案 0 :(得分:0)
易于测试的数据库方案,可以在每个测试用例之前和之后轻松进行设置。
我一直在测试范围内使用嵌入式H2数据库,并在每个测试案例之前通过SQL脚本设置数据库。
首先,在pom.xml上添加对测试范围的H2依赖(您正在使用Maven吗?)。
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
然后,设置您的JUnit测试类。
SampleTestClass.java
@SpringBootTest // Allows you to autowire beans on your test class
@AutoConfigureTestDatabase // Configures a database on test scope instead of your regular database config.
@RunWith(SpringRunner.class) // Runs test context with SpringRunner.class
@SqlGroup({ // Setups .sql files to be run on specific triggers. In this case, before each test method the script will be ran.
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:beforeTest.sql"),
})
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) // The spring application context will be considered "dirty" before each test method, and will be rebuilt. It means that
// your autowired beans will not carry any data between test cases.
public class SampleTestClass {
// write your test cases here...
}
@Before
注释的方法。该方法将在每个测试用例之前运行。答案 1 :(得分:0)
我的测试只是从数据库读取的,我只想在所有测试之前初始化数据库一次。我的最终解决方案:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
@Transactional
class MyTest {
@Autowired
private DbCreatorService dbCreatorService;
@BeforeAll
void initDatabase() {
dbCreatorService.initDB()
}
}