DBUnit load dataset and rollback - java

I'm having troubles setting this to work. Basically I want when a tests finishes running for the database to be in the exact same state as before. This happens when using Spring/Hibernate managed sessions and connections, but not for DBUnit. I've tried lots of things and at this point I was doing something like wrapping the shared datasource in TransactionAwareDataSourceProxy and executing the load dataset manually instead of using #DatabaseSetup.
this.databaseConnection = new DatabaseConnection(dataSource.getConnection());
IDataSet xmlFileDataSet = new FlatXmlDataSetBuilder().build(getClass().getResourceAsStream("/dataset.xml"));
DatabaseOperation.REFRESH.execute(databaseConnection, xmlFileDataSet);
And it simply doesn't work. I've checked the dataSource object and it's a TransactionAwareDataSourceProxy instance so everything should be in place. All the data in the dataset is committed and persisted and all the data added/modified inside the spring managed session is not.
Does anyone have a clue what I might be missing or any did this before and ran into the same troubles?
Current code (tried with and without TransactionAwareDataSourceProxy).
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {
RecipeManagementITConfig.class,
SpringJpaTestConfig.class,
DatabaseITConfig.class
},
initializers = {PleaseWork.class})
#TestExecutionListeners({
DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
#TransactionConfiguration(defaultRollback = true)
#Transactional
public class DefaultIngredientServiceIT {
#Autowired
protected DataSource dataSource;
#Before
public void init() throws Exception {
System.out.println("> " + dataSource); // org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy#d4ce346
dbTester = new DataSourceDatabaseTester(dataSource);
dbTester.setDataSet(getDataSet());
dbTester.setSetUpOperation(DatabaseOperation.REFRESH);
dbTester.onSetup();
}
#After
public void destroy() throws Exception {
dbTester.onTearDown();
}
private IDataSet getDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(getClass().getResourceAsStream("/dataset.xml"));
}
#Transactional
#Test
public void testDeletionOfIngredients() {
(...)
}
}

Try using a DataSourceDatabaseTester like this:
public class MyTestCase {
#Autowired
private DataSource dataSource;
private IDatabaseTester dbTester;
#Before
public void init() throws Exception {
dbTester = new DataSourceDatabaseTester( getDataSource() );
dbTester.setDataSet( getDataSet() );
dbTester.onSetUp();
}
#Destroy
public void destroy() throws Exception {
dbTester.onTearDown();
}
private IDataSet getDataSet() throws Exception {
return new FlatXmlDataSet(new FileInputStream("dataset.xml"));
}
}

Related

Why doesn't my #Transactional method rollback when testing?

I have #transactional method that seems to be working (rolling back) if run the actual service and provide inputs that would cause a run-time error. If I create a Test for that method that throws a run-time error it doesn't seem to rollback anymore. Any idea why this doesn't work while testing?
it's somthing like:
#Service
public class SampleServiceImpl implements SampleService {
private final RepoA repoA;
private final RepoB repoB;
public SampleServiceImpl(RepoA repoA, RepoB repoB) {
this.repoA = repoA,
this.repoB = repoB
}
#Transactional
#Override
public void addItems() {
repoA.save(new ItemA(1,'name1')); //works
repoB.save(new ItemB(2,'name2')); //throws run-time error
}
}
#RunWith(SpringRunner.class)
#DataJpaTest
public class Tests {
#Autowired
private RepoA repoA;
#Mock
private Repob repoBMock;
#Test
public void whenExceptionOccurrs_thenRollsBack() {
var service = new SampleService(repoA, repoBMock);
Mockito.when(repoBMock.save(any(ItemB.class))).thenThrow(new RuntimeException());
boolean exceptionThrown = false;
try {
service.addItems()
} catch (Exception e) {
exceptionThrown = true;
}
Assert.assertTrue(exceptionThrown);
Assert.assertFalse(repoA.existsByName('name1')); // this assertion fails because the the first item still exists in db
}
}
Just add annotation Rollback and set the flag to false.
#Test
#Rollback(false)

Spring database transaction not committing data in Db

I have created a project with spring boot. I have hikariConfig to create the data source for connection pooling with the autocommmit property set as false. Doing batch insert with jdbcTemplate running inside method annotated with #Transaction for DataSourceTransactionManager. I am unable to see the data getting inserted in Db after the program execution. If I make the autocommit true in hikariconfig it works fine.
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Component
#EnableTransactionManagement
public class DataSourceConfig {
#Bean (name = "dateSourceForSqlServer")
public DataSource dataSourceForSqlServer () {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setConnectionTimeout(10000L);
hikariConfig.setIdleTimeout(10000L);
hikariConfig.setMinimumIdle(1);
hikariConfig.setMaximumPoolSize(1);
hikariConfig.setMaxLifetime(600000L);
hikariConfig.setConnectionTestQuery("select 1");
hikariConfig.setValidationTimeout(4000L);
hikariConfig.setJdbcUrl("jdbc:sqlserver://localhost:1433;database=invt_mgmt");
hikariConfig.setUsername("sa");
hikariConfig.setPassword("sql_server_pass_123");
hikariConfig.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
hikariConfig.setAutoCommit(false);
return new HikariDataSource(hikariConfig);
}
#Bean (name = "jdbcTemplateForSqlServer")
public JdbcTemplate jdbcTemplateForSqlServer () {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSourceForSqlServer());
return jdbcTemplate;
}
#Primary
#Bean(name = "invtMgmtTxMangerForSqlServer")
public DataSourceTransactionManager transactionManager() {
DataSourceTransactionManager manager = new DataSourceTransactionManager();
manager.setDataSource(dataSourceForSqlServer());
return manager;
}
}
#Component
public class startBean {
#Autowired
private Business Business;
#PostConstruct
public void startApp() throws SQLException {
Business.insertContainerHierarchy();
Business.insertContainerHierarchy();
}
}
#Component
class public Business {
#Autowired
#Qualifier("jdbcTemplateForSqlServer")
private JdbcTemplate jdbcTemplateForSqlServer;
String insertIntStudent = "INSERT INTO student (id, name) Values(?, ?)";
#Transactional(value = "invtMgmtTxMangerForSqlServer")
public void insertContainerHierarchy () throws SQLException {
System.out.println(TransactionSynchronizationManager.isActualTransactionActive());
System.out.println(TransactionSynchronizationManager.getCurrentTransactionName());
Date start = new Date();
for (int i = 0; i < 500; i++) {
System.out.println(i);
jdbcTemplateForSqlServer.batchUpdate(insertIntStudent, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setInt(1, i);
ps.setString(2, String.valueOf(i));
}
#Override
public int getBatchSize() {
return 1000;
}
});
}
System.out.println(new Date().getTime() - start.getTime());
}
}
I have used TransactionSynchronizationManager.isActualTransactionActive() which is returing true when the method is executed.
Q1. Why the data is not getting inserted, Transaction is supposed to autocommit once the method is executed?
Q2. In case spring transaction is getting used will database connection autocommit value make any difference?
Q3. How currently I am able to insert with autocommit set to true?
You are trying to invoke a transaction-wrapped proxy from within the #PostConstruct method. For that bean, all the initialization may be complete but not necessarily for the rest of the context. Not all proxies may be set at that point.
I would suggest implementing the ApplicationListener<ContextRefreshedEvent> interface in order to trigger any data creation inside that class. This will ensure it will be called after the entire context has been set-up:
#Component
public class OnContextInitialized implements
ApplicationListener<ContextRefreshedEvent> {
#Autowired
private Business Business;
#Override public void onApplicationEvent(ContextRefreshedEvent event) {
Business.insertContainerHierarchy();
Business.insertContainerHierarchy();
}
}

Spring 4.07 Junit Test and Autowired

Hi I'm using Spring and CDI.
In my unit test I want to test a Class that uses the #Autowired annotation.
Problem is if I create a instance of this class and call a method all annotated objects are null.
In basic the annotation works. Just whithin my unit test it doesn't
This is my Unit Test. In here Autowired works. In my test I create an instance of the DemoConsumerBean.class and call the method requestJobsFromPublishedJobsApi in here I have also some Autowired declaration. Problem is all instances are null!
#RunWith(SpringJUnit4ClassRunner.class)
#ActiveProfiles("development")
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, FirstbirdTestExecutionListener.class, FlywayTestExecutionListener.class })
#ContextConfiguration(locations = { "classpath:hibernate-spring.xml" })
#FlywayTest
public class DemoConsumerBeanTest extends AbstractJUnit4SpringContextTests {
#Autowired
private CustomerManager customerManager;
#Autowired
private DemoDetailsManager demoDetailsManager;
#Before
public void setup() {
CamelContext context = new DefaultCamelContext();
exchange = new DefaultExchange(context);
}
#Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
DemoConsumerBean demoConsumerBean = new DemoConsumerBean();
customer = new Customer();
customer.setCustomerId(15);
customer = customerManager.getCustomerById(customer);
// This one works
DemoDetails demoDetails = demoDetailsManager.getDemoDetailsByCustomerId(customer);
demoConsumerBean.requestJobsFromPublishedJobsApi(exchange, customer);
PublishedJobs apiJobs = exchange.getIn().getBody(PublishedJobs.class);
assertNotNull(apiJobs);
}
}
public class DemoConsumerBean {
#Autowired
protected CustomerManager customerManager;
#Autowired
protected DemoDetailsManager demoDetailsManager;
#Autowired
protected MessageLogManager messageLogManager;
public void requestJobsFromPublishedJobsApi(Exchange exchange, Customer customer) throws NoSuchDataException {
//this one is null!
DemoDetails demoDetails = demoDetailsManager.getDemoDetailsByCustomerId(customer);
PublishedJobs jobs = null;
if (demoDetails == null || StringUtils.isBlank(demoDetails.getDemoApiUrl())) {
throw new NoSuchDataException("No demo data found for customer " + customer.getCustomerFirstbirdId());
}
....
}
}
Using new in new DemoConsumerBean(); bypasses spring, that's your issue.
Either use a DemoConsumerBean instance from spring (i.e. autowired in the test) or add setters and use them to "manually autowire" in DemoConsumerBean in your test:
#Test
public void requestJobsFromPublishedJobsApiTest() throws NoSuchDataException {
DemoConsumerBean demoConsumerBean = new DemoConsumerBean();
demoConsumerBean.setCustomerManager(this.customerManager)
// etc
Some reading: Spring framework reference - The IoC container

Spring Dao-Test defaultRollback not working

I got a problem with my Dao-Test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations={"/cmn-dao-spring.xml"})
#TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public class ScoreDaoTest extends TestCase {
#Autowired
private ScoreDao mScoreDao;
#Autowired
private ScoreCreator mScoreCreator;
#Autowired
private QuestionCreator mQuestionCreator;
#Override
protected void setUp() throws Exception {
super.setUp();
}
#Test
public void testLoadAllScore() throws Exception {
List<Score> lAllScore = mScoreDao.loadAllScore(0, 0);
Assert.assertTrue(lAllScore.isEmpty());
}
#Test
public void testSaveScore() throws Exception {
Question question = mQuestionCreator.createQuestion(49954854L, new Date(), "Wer bist Du?", "Jörg", "Anja", "Stefan", "Willi", 3, true, false, 1, "DE", "DE_QZ");
Assert.assertNotNull(question);
mScoreDao.saveScore(mScoreCreator.createScore(-1L, null, "Stefan", 1033, 27, "Wuhuuuu", question));
List<Score> lAllScore = mScoreDao.loadAllScore(0, 1);
Assert.assertFalse(lAllScore.isEmpty());
}
}
Every time I run my test class the data is saved permanently. But I don't want that for my test classes.
I don't see the problem.
Your tests are not transactional, so Spring doesn't have any transaction to rollback.
Add #Transactional to the test methods (or to the test class if you want all its test methods to be transactional).

Problems using DbUnit with Spring TestContext

I'm trying to test my DAO layer (which is built on JPA) in separation. In the unit test, I'm using DbUnit to populate the database and Spring Test to get an instance of ApplicationContext.
When I tried to use the SpringJunit4ClassRuner, the ApplicationContext got injected, but the DbUnit's getDataSet() method never got called.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...
Then I tried to remove the #RunWith annotation, that removed the problems with getDataSet() method. But now I no longer get ApplicationContext instance injected. I tried to use the #TestExecutionListeners annotation, which is supposed to configure the DependencyInjectionTestExecutionListener by default, but the AppContext still doesn't get injected.
#TestExecutionListeners
#ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
...
Does anyone have any ideas? Is it generally a bad idea to combine these two frameworks?
EDIT: here is the rest of the source for the test class:
#TestExecutionListeners
#ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
static final String TEST_DB_PROPS_FILE = "testDb.properties";
static final String DATASET_FILE = "testDataSet.xml";
static Logger logger = Logger.getLogger( SimpleJPATest.class );
private ApplicationContext ctx;
public SimpleJPATest() throws Exception {
super();
setDBUnitSystemProperties(loadDBProperties());
}
#Test
public void testSimple() {
EntityManagerFactory emf = ctx.getBean("entityManagerFactory", EntityManagerFactory.class);
EntityManager em = emf.createEntityManager();
GenericDAO<Club> clubDAO = new JpaGenericDAO<Club>(ClubEntity.class, "ClubEntity", em);
em.getTransaction().begin();
Collection<Club> allClubs = clubDAO.findAll();
em.getTransaction().commit();
assertEquals(1, allClubs.size());
}
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
private void setDBUnitSystemProperties(Properties props) {
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
props.getProperty("db.driver"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
props.getProperty("db.url"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
props.getProperty("db.username"));
System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
props.getProperty("db.password"));
}
private Properties loadDBProperties() throws Exception {
URL propsFile = ClassLoader.getSystemResource(TEST_DB_PROPS_FILE);
assert (propsFile != null);
Properties props = new Properties();
props.load(propsFile.openStream());
return props;
}
#Override
protected void setUpDatabaseConfig(DatabaseConfig config) {
config.setProperty( DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
new HsqldbDataTypeFactory() );
}
#Override
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.CLEAN_INSERT;
}
#Override
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE_ALL;
}
#Override
protected IDataSet getDataSet() throws Exception {
logger.debug("in getDataSet");
URL dataSet = ClassLoader.getSystemResource(DATASET_FILE);
assert (dataSet != null);
FlatXmlDataSet result = new FlatXmlDataSetBuilder().build(dataSet);
return result;
}
}
I've used these two frameworks together without any issues. I've had to do some things a little different from the standard though to get it to work:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:applicationContext.xml" })
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class })
public class MyDaoTest extends DBTestCase {
#Autowired
private MyDao myDao;
/**
* This is the underlying BasicDataSource used by Dao. If The Dao is using a
* support class from Spring (i.e. HibernateDaoSupport) this is the
* BasicDataSource that is used by Spring.
*/
#Autowired
private BasicDataSource dataSource;
/**
* DBUnit specific object to provide configuration to to properly state the
* underlying database
*/
private IDatabaseTester databaseTester;
/**
* Prepare the test instance by handling the Spring annotations and updating
* the database to the stale state.
*
* #throws java.lang.Exception
*/
#Before
public void setUp() throws Exception {
databaseTester = new DataSourceDatabaseTester(dataSource);
databaseTester.setDataSet(this.getDataSet());
databaseTester.setSetUpOperation(this.getSetUpOperation());
databaseTester.onSetup();
}
/**
* Perform any required database clean up after the test runs to ensure the
* stale state has not been dirtied for the next test.
*
* #throws java.lang.Exception
*/
#After
public void tearDown() throws Exception {
databaseTester.setTearDownOperation(this.getTearDownOperation());
databaseTester.onTearDown();
}
/**
* Retrieve the DataSet to be used from Xml file. This Xml file should be
* located on the classpath.
*/
#Override
protected IDataSet getDataSet() throws Exception {
final FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
builder.setColumnSensing(true);
return builder.build(this.getClass().getClassLoader()
.getResourceAsStream("data.xml"));
}
/**
* On setUp() refresh the database updating the data to the data in the
* stale state. Cannot currently use CLEAN_INSERT due to foreign key
* constraints.
*/
#Override
protected DatabaseOperation getSetUpOperation() {
return DatabaseOperation.CLEAN_INSERT;
}
/**
* On tearDown() truncate the table bringing it back to the state it was in
* before the tests started.
*/
#Override
protected DatabaseOperation getTearDownOperation() {
return DatabaseOperation.TRUNCATE_TABLE;
}
/**
* Overridden to disable the closing of the connection for every test.
*/
#Override
protected void closeConnection(IDatabaseConnection conn) {
// Empty body on purpose.
}
// Continue TestClass here with test methods.
I've had to do things a little more manual than I would like, but the same scenario applies if you try to use the JUnit Parameterized runner with Spring (in that case you have to start the TextContext manually). The most important thing to note is that I override the closeConnection() method and leave it blank. This overrides the default action of closing the dataSource connection after each test which can add unnecessary time as the connection will have to be reopened after every test.

Categories

Resources