I am testing my add method for thread safety using multi-threads.
I open 3 threads, 2 of which should fail.
The test would succeed when only one row is added to the db.
Given my output log, I have one insert suceeding and 2 failing.
That's just what I'm expecting.
But the test fails because when I retrieve the list, the number of rows is still the same.
From what I understand, using AbstractTransactionalDataSourceSpringContextTests guarantees that the session stays as long as the unit test method, so the added row should be visible to the retrieving method.
I also added a commit after the addGrouping method call, but the result is still the same.
Any ideas
output log:
iie:null
iie:[[errors.alreadyExists Barkada]]
iie:[[errors.alreadyExists Barkada]]
Code:public class GroupingFacadeTransactionTest extends AbstractTransactionalDataSourceSpringContextTests { public void onSetUpBeforeTransaction() throws Exception { deleteFromTables(new String[]{"unit ORDER by super_unit_code DESC", "grouping"}); jdbcTemplate.batchUpdate(SpringUtil.extractSQLFromFile(MainTest.DIR + "employee/grouping.sql")); } protected String[] getConfigLocations() { return new String[]{"/WEB-INF/applicationContext.xml"}; } /* * To replicate failure, delete synchronized keyword in * GroupingFacade.confirmAddGrouping and add Thread.sleep(500) between * isExisting and checking for duplicate. Based on Pentium4 2.2Ghz */ public void testaddGroupingMultiThreaded() throws Exception { Runnable r = new Runnable() { public void run() { try { Grouping gb = new Grouping(); gb.setGroupingName("Barkada"); InvalidInputException iie = GroupingFacade.addGrouping(gb); System.out.println("iie:" + iie); } catch (Exception e) { System.out.println("error:" + e); } } }; List al = GroupingFacade.getGroupingList(); assertEquals(3, al.size()); ThreadGroup tg = new ThreadGroup("run"); for (int i = 0; i < 3; i++) { Thread t = new Thread(tg, r); t.start(); } boolean isRunning = true; while (isRunning) { isRunning = tg.activeCount() != 0; } al = GroupingFacade.getGroupingList(); assertEquals(4, al.size()); Grouping gv = (Grouping) al.get(0); assertEquals("Barkada", gv.getGroupingName()); } }


Reply With Quote