Java spring Junit Transaction不会回滚数据库

时间:2016-11-13 18:07:40

标签: java spring junit transactions hsqldb

我想在每次测试后回滚数据库,但它不起作用,我尝试了不同类型的事务管理配置。 createNewItem method对象仍在其他测试中显示。

回滚的目标是让每个测试具有相同的数据库对象和预期的新ID

ContextConfiguration:

 @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());
}

1 个答案:

答案 0 :(得分:0)

这就是我通常注释我的测试类的方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAUnitTestConfiguration.class })
@Transactional //rollback if exception occurs during test method
@TransactionConfiguration(defaultRollback = true) //rollback at end of method
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public class FooBarTest {
}

将@TransactionConfiguration(defaultRollback = true)添加到测试类中。

我的交易配置:

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import ch.ams.pois.repository.AuthTokenRepository;
import ch.ams.pois.repository.GroupRepository;
import ch.ams.pois.repository.InvitationRepository;
import ch.ams.pois.repository.LocationRepository;
import ch.ams.pois.repository.UserRepository;


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = JPAConfiguration.JPA_REPOSITORIES_BASE_PACKAGES, 
includeFilters = @ComponentScan.Filter(value = { 
        UserRepository.class, LocationRepository.class, 
        GroupRepository.class, AuthTokenRepository.class, 
        InvitationRepository.class }, 
        type = FilterType.ASSIGNABLE_TYPE))
public class JPAUnitTestConfiguration extends JPAConfiguration {

    @Bean
    public DataSource dataSource() throws SQLException {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }
}

持久层的依赖关系:

<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.3.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.3.173</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.2-1003-jdbc4</version>
        </dependency>