I want to rollback database after each test but it doesn't work, I've tried different types of Transaction management configs.
The createNewItem method object is still showing on other tests.
The goal of the rollback is to have the have exacly the same database objects and expected new ids on every test
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;
}
Junit test with hsqldb:
@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());
}