/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.cache.pojo.notification;

import static org.testng.AssertJUnit.assertEquals;

import org.jboss.cache.pojo.PojoCache;
import org.jboss.cache.pojo.PojoCacheFactory;
import org.jboss.cache.pojo.impl.CacheListenerAdaptor;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

// $Id: ObjectTest.java 4698 2007-10-26 18:30:20Z jason.greene@jboss.com $

/**
 * Tests that CacheListenerAdaptor is attached properly.
 *
 * @author Jason T. Greene
 */
@Test(groups = {"functional"})
public class ListenerCountTest
{
   protected PojoCache cache;

   @BeforeMethod(alwaysRun = true)
   protected void setUp() throws Exception
   {
      String configFile = "META-INF/local-service.xml";
      boolean toStart = false;
      cache = PojoCacheFactory.createCache(configFile, toStart);
      cache.start();
   }

   @AfterMethod(alwaysRun = true)
   protected void tearDown() throws Exception
   {
      cache.stop();
   }

   public void testAddRemoveListener() throws Exception
   {    
      assertEquals(0, getAdaptorCount());
      
      Object listener1 = new Listener();
      cache.addListener(listener1);
      assertEquals(1, getAdaptorCount());
      
      Object listener2 = new Listener();
      cache.addListener(listener2);
      assertEquals(1, getAdaptorCount());
      
      cache.removeListener(listener1);      
      assertEquals(1, getAdaptorCount());
      
      cache.removeListener(listener2);      
      assertEquals(0, getAdaptorCount());
   }

   private int getAdaptorCount()
   {
      int count = 0;
      for (Object listener : cache.getCache().getCacheListeners())
         if (listener instanceof CacheListenerAdaptor)
            count++;
      
      return count;
   }
}