FileDocCategorySizeDatePackage
MockInterceptorTest.javaAPI DocExample1984Mon Apr 25 08:20:18 BST 2005None

MockInterceptorTest.java

import com.springbook.InterceptMe;
import com.springbook.LogEvent;
import com.springbook.interceptors.LoggingAround;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.aopalliance.aop.Advice;
import org.springframework.aop.framework.ProxyFactory;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Session;

public class MockInterceptorTest extends TestCase implements InterceptMe {
   public void interceptThisMethod() {
      // empty method
   }

    public void testLoggingInterceptor() throws Exception {
      MockControl factoryControl = MockControl.createControl(SessionFactory.class);
      MockControl sessionControl = MockControl.createControl(Session.class);

      SessionFactory mockFactory =
            (SessionFactory)factoryControl.getMock();
      Session mockSession = (Session)sessionControl.getMock();
      // this sequence will execute once before the target method...
      mockFactory.openSession();
      factoryControl.setReturnValue(mockSession);
      mockSession.save(new LogEvent());
      sessionControl.setMatcher(MockControl.ALWAYS_MATCHER);
      sessionControl.setReturnValue(null);
      mockSession.close();
      sessionControl.setReturnValue(null);
      // and once after
      mockFactory.openSession();
      factoryControl.setReturnValue(mockSession);
      mockSession.save(new LogEvent());
//      sessionControl.setMatcher(MockControl.ALWAYS_MATCHER);
      sessionControl.setReturnValue(null);
      mockSession.close();
      sessionControl.setReturnValue(null);
      factoryControl.replay();
      sessionControl.replay();


      Advice advice = new LoggingAround();
      ((LoggingAround)advice).setFactory(mockFactory);
      ProxyFactory proxyFactory = new ProxyFactory(this);
      proxyFactory.addAdvice(advice);
      InterceptMe target = (InterceptMe)proxyFactory.getProxy();
      target.interceptThisMethod();

      factoryControl.verify();
      sessionControl.verify();

   }

}