Announcement Announcement Module
Collapse
No announcement yet.
multi-threaded junit Spring test Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • multi-threaded junit Spring test

    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 &#40;int i = 0; i < 3; i++&#41; &#123;
    			Thread t = new Thread&#40;tg, r&#41;;
    			t.start&#40;&#41;;
    		&#125;
    		boolean isRunning = true;
    		while &#40;isRunning&#41; &#123;
    			isRunning = tg.activeCount&#40;&#41; != 0;
    		&#125;
    		al = GroupingFacade.getGroupingList&#40;&#41;;
    		assertEquals&#40;4, al.size&#40;&#41;&#41;;
    		Grouping gv = &#40;Grouping&#41; al.get&#40;0&#41;;
    		assertEquals&#40;"Barkada", gv.getGroupingName&#40;&#41;&#41;;
    	&#125;
    
    &#125;
Working...
X