Announcement Announcement Module
Collapse
No announcement yet.
@Async in unit test Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Async in unit test

    Hi

    Is it possible to have a junit test method with the @Async annotation?

    I am trying to generate concurrent access to a service.
    In order to that I was thinking off calling an @Async method that calls this service.

    I am using 3.0.3.RELEASE.
    I have this declaration in my xml configuration: <task:annotation-driven />

    Code:
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    @Transactional
    @TransactionConfiguration
    public class CampaignServiceTest
    {
    	@Autowired
    	private xxService xxService;
    	
    	@Test
    	public void testConcurrency() throws InterruptedException, ExecutionException
    	{
    		List<Boolean> results = new ArrayList<Boolean>();
    		Parameter parameter = new parameter();
    		
    		for (int i = 0; i < 200; i++)
    		{
    			System.out.println("start "+i);
    			results.add(consume(parameter, i).get().booleanValue());
    		}
    		
    		for (Boolean value : results)
    		{
    			assertTrue("the consumer finished with an error", value);
    		}
    	}
    	
    	@Async
    	public Future<Boolean> consume(Parameter parameter, int number)
    	{
    		try
    		{
    			xxService.handleOperation(parameter);
    			
    			Thread.sleep((int) (Math.random() * 1000));
    			
    			System.out.println("end " + number);
    			
    			return new AsyncResult<Boolean>(true);
    		}
    		catch (Exception e)
    		{
    			System.out.println("end " + number);
    			
    			return new AsyncResult<Boolean>(false);
    		}
    	}
    }
    The ouput of that test shows that there is no AsyncTask at all.
    Aach call is done one after the others.

    Any help or suggestion will be appreciated.
    Regards

  • #2
    No...

    The annotation only works for beans defined in y our app context your unit test is not part of your app context...

    Comment


    • #3
      Thread and concurrency access

      What is the best way to achieve that goal (test concurrency access).
      I tried to create thread but it generate transactions problems.

      Code:
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
      @Transactional
      @TransactionConfiguration
      public class CampaignServiceTest
      {
      	@Autowired
      	private xxService xxService;
      	
      	@Test
      	public void testConcurrency() throws InterruptedException, ExecutionException
      	{
      		final int consumerCount = 200;
      		ExecutorService executor = Executors.newFixedThreadPool(consumerCount);
      		List<CampaignConsumer> consumers = new ArrayList<CampaignConsumer>(consumerCount);
      		Parameter parameter = new parameter();
      		
      		for (int i = 0; i < consumerCount; i++)
      		{
      			CampaignConsumer campaignConsumer = new CampaignConsumer();
      			campaignConsumer.parameter = parameter;
      			
      			consumers.add(campaignConsumer);
      			executor.execute(campaignConsumer);
      		}
      		
      		executor.shutdown();
      		executor.awaitTermination(5, TimeUnit.MINUTES);//wait for executor end durring 5 minutes
      		
      		for (CampaignConsumer consumer : consumers)
      		{
      			assertFalse("the consumer finished with an error", consumer.hasError);
      		}
      	}
      	
      	class CampaignConsumer implements Runnable
      	{
      		protected Parameter parameter = null;
      		protected boolean hasError = false;
      		
      		@Override
      		public void run()
      		{
      			try
      			{
      				xxService.handleOperation(parameter);
      			}
      			catch (Exception e)
      			{
      				hasError = true;
      			}
      		}
      	}
      }

      Comment


      • #4
        Concurrent testing is a pain (imho), I suggest google as there are some articles (and junit extensions) out there which can help you...

        Comment


        • #5
          synchronization on service

          I checked on the net, I am going to make integration test using jmeter.
          That will take some time.

          Is it possible to add synchronization (with synchronized or lock) in service ?

          My services are thread safe but I need to make sure that an specific update that involve payment with credit point is made without concurrency problem.

          Regards

          Comment


          • #6
            You can always start threads yourself. I recently also came a cross a junit test which enables multithreaded testing, this is also an article which explains something about it.

            You don't want synchronize in your service, unless you want poor performance... Your service is thread safe so it shouldn't matter.

            Comment


            • #7
              Thread and Thransaction

              Hi

              I am still investigating a proper way to test concurrency access.
              I would to know is transactions are associated to thread ?.

              Regards

              Comment

              Working...
              X