【发布时间】:2017-03-27 09:39:27
【问题描述】:
我想在每次测试后回滚数据库,但它不起作用,我尝试了不同类型的事务管理配置。
createNewItem method 对象仍在其他测试中显示。
回滚的目标是让每个测试都拥有完全相同的数据库对象和预期的新 ID
上下文配置:
@Configuration
@EnableJpaRepositories("se.system.repository")
@EnableTransactionManagement
public class ContextConfiguration{
@Bean(name = "hsqldb")
public DataSource InMemoryDataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase database = builder.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:se/system/sql/create-db.sql")
.addScript("classpath:se/system/sql/insert-data.sql").build();
return database;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory factory) {
return new JpaTransactionManager(factory);
}
@Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setDatabase(Database.HSQL);
adapter.setShowSql(false);
adapter.setGenerateDdl(false);
return adapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(InMemoryDataSource());
factory.setJpaVendorAdapter(jpaVendorAdapter());
factory.setPackagesToScan("se.system.model");
return factory;
}
使用 hsqldb 进行 Junit 测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ContextConfiguration.class })
@TestExecutionListeners
@Transactional
public class ServiceTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private static Service service;
private static AnnotationConfigApplicationContext context;
@BeforeClass
public static void setup() {
context = new AnnotationConfigApplicationContext();
context.register(ContextConfiguration.class);
context.scan("se.system");
context.refresh();
Service = context.getBean(Service.class);
}
@Test
public void createNewItem() {
System.out.println(((List<Item>) service.getAllitem()).size());
Item item = Service
.saveOrUpdateItem(new Item("Title", "Description"));
System.out.println(Item);
assertEquals(new Long(4L), Item.getId());
}
【问题讨论】:
-
嗨,您在哪里将 autocommit 设置为 false?
-
嘿,我也在找那个,但是我没有找到把它变成假的地方,所以我认为它默认已经是假的了。
-
能否贴出带有saveOrUpdateItem方法的服务类代码?
-
即使测试确实回滚,即取消插入 Item 对象,如果它是由标识列生成的,id 生成器也不会回滚。所以在同一个数据库上运行两次测试如果第一次成功,第二次肯定会失败。
-
好的,但如果我将它们全部打印出来,测试后数据库对象仍然存在
标签: java spring junit transactions hsqldb