Replaced easymock by mockito.
authorErik Brakkee <erik@brakkee.org>
Thu, 10 Jul 2008 13:21:25 +0000 (13:21 +0000)
committerErik Brakkee <erik@brakkee.org>
Thu, 10 Jul 2008 13:21:25 +0000 (13:21 +0000)
pom.xml
support/general/src/test/java/org/wamblee/io/DirectoryMonitorTest.java
support/general/src/test/java/org/wamblee/observer/ObservableTest.java
support/general/src/test/java/org/wamblee/test/EasyMockMatchers.java [deleted file]
support/general/src/test/java/org/wamblee/test/ResettableMock.java [new file with mode: 0644]
system/general/src/test/java/org/wamblee/system/container/ContainerTest.java
system/general/src/test/java/org/wamblee/system/graph/CompositeEdgeFilterTest.java
system/general/src/test/java/org/wamblee/system/graph/GraphTest.java

diff --git a/pom.xml b/pom.xml
index 52758f75c47ca971b18b2f2c1040e293e2bbeaa2..659fb8f0055d081a8517939b53ee4f1006a31072 100644 (file)
--- a/pom.xml
+++ b/pom.xml
             <version>2.2</version>
             <scope>test</scope>
         </dependency>
-        <dependency>
-            <groupId>org.easymock</groupId>
-            <artifactId>easymock</artifactId>
-            <version>2.3</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.easymock</groupId>
-            <artifactId>easymockclassextension</artifactId>
-            <version>2.3</version>
-            <scope>test</scope>
-        </dependency>
         <dependency>
             <groupId>org.apache.derby</groupId>
             <artifactId>derby</artifactId>
             <artifactId>mysql-connector-java</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+            <version>1.3</version> 
+            <scope>test</scope>
+        </dependency>
+
         <!-- dependency>
           <groupId>org.testng</groupId>
           <artifactId>testng</artifactId>
index 835c696305fcd35825c03b70b3b55a412c34077f..347857da528b1ef04905ab2a630c1c3f122cb5c3 100644 (file)
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
- */ 
+ */
 package org.wamblee.io;
 
-import org.apache.oro.io.AwkFilenameFilter;
-import org.easymock.EasyMock;
-
+import static org.mockito.Mockito.*;
 import junit.framework.TestCase;
 
+import org.apache.oro.io.AwkFilenameFilter;
+import org.wamblee.test.ResettableMock;
+
 public class DirectoryMonitorTest extends TestCase {
 
        private static final String REGEX = "^.*\\.txt$";
        private static final String FILE1 = "file1.txt";
 
        private TestData _data;
-       private DirectoryMonitor.Listener _listener;
+       private ResettableMock<DirectoryMonitor.Listener> _listener;
+
        private DirectoryMonitor _monitor;
 
        @Override
@@ -34,97 +36,88 @@ public class DirectoryMonitorTest extends TestCase {
                super.setUp();
                _data = new TestData(this);
                _data.clean();
-               _listener = EasyMock.createStrictMock(DirectoryMonitor.Listener.class);
+               _listener = new ResettableMock<DirectoryMonitor.Listener>(
+                               DirectoryMonitor.Listener.class);
                _monitor = new DirectoryMonitor(_data.getRoot(), new AwkFilenameFilter(
-                               REGEX), _listener);
+                               REGEX), _listener.getProxy());
        }
 
        public void testEmptyDir() {
                // Nothing is expected to be called.
                for (int i = 0; i < 10; i++) {
-                       EasyMock.replay(_listener);
                        _monitor.poll();
-                       EasyMock.verify(_listener);
-                       EasyMock.reset(_listener);
+                       verifyNoMoreInteractions(_listener.getMock());
                }
        }
 
        public void testFileCreated() {
-               _listener.fileCreated(_data.getFile(FILE1));
-               EasyMock.replay(_listener);
                _data.createFile(FILE1, "hello");
                _monitor.poll();
-               EasyMock.verify(_listener);
+               verify(_listener.getMock()).fileCreated(_data.getFile(FILE1));
        }
 
        public void testFileDeleted() {
                _data.createFile(FILE1, "hello");
                _monitor.poll();
-
-               EasyMock.reset(_listener);
+               _listener.reset();
 
                _data.deleteFile(FILE1);
-               _listener.fileDeleted(_data.getFile(FILE1));
-               EasyMock.replay(_listener);
                _monitor.poll();
-               EasyMock.verify(_listener);
+
+               verify(_listener.getMock()).fileDeleted(_data.getFile(FILE1));
+               verifyNoMoreInteractions(_listener.getMock());
        }
-       
-       public void testFileChanged() throws InterruptedException { 
+
+       public void testFileChanged() throws InterruptedException {
                _data.createFile(FILE1, "hello");
                _monitor.poll();
-               EasyMock.reset(_listener);
-               
+               _listener.reset();
+
                Thread.sleep(2000);
                _data.deleteFile(FILE1);
                _data.createFile(FILE1, "bla");
-               
-               _listener.fileChanged(_data.getFile(FILE1));
-               EasyMock.replay(_listener);
+
                _monitor.poll();
-               EasyMock.verify(_listener);
+               verify(_listener.getMock()).fileChanged(_data.getFile(FILE1));
+               verifyNoMoreInteractions(_listener.getMock());
        }
-       
+
        public void testFileFilterIsUsed() {
-               _monitor.poll(); 
-               
+               _monitor.poll();
+
                _data.createFile("file.xml", "hello");
-               EasyMock.replay(_listener); 
                _monitor.poll();
-               EasyMock.verify(_listener);
+               verifyNoMoreInteractions(_listener.getMock());
        }
-       
-       public void testDirectoryIsIgnored() { 
+
+       public void testDirectoryIsIgnored() {
                _monitor.poll();
                _data.createDir(FILE1);
-               EasyMock.replay(_listener); 
                _monitor.poll();
-               EasyMock.verify(_listener);
+               verifyNoMoreInteractions(_listener.getMock());
        }
-       
+
        public void testExceptionsWIllLeadToRepeatedNotifications() { 
                _monitor.poll();
                _data.createFile(FILE1, "hello");
                
-               _listener.fileCreated(_data.getFile(FILE1));
-               EasyMock.expectLastCall().andThrow(new RuntimeException());
-               EasyMock.replay(_listener);
+               stubVoid(_listener.getMock()).toThrow(new RuntimeException()).on().
+                fileCreated(_data.getFile(FILE1));
+               
                try { 
                    _monitor.poll();
                } catch (RuntimeException e) { 
-                       EasyMock.verify(_listener);
-                       EasyMock.reset(_listener);
+                       _listener.reset(); 
                        
-                       // polling again should lead to the same filecreated call. 
-                       // this time no exception is thrown. 
+                       // polling again should lead to the same filecreated call.
+                       // this time no exception is thrown.
                        
-                       _listener.fileCreated(_data.getFile(FILE1));
-                       EasyMock.replay(_listener);
                        _monitor.poll();
-                       EasyMock.verify(_listener);
+                       verify(_listener.getMock()).fileCreated(_data.getFile(FILE1));
+                       verifyNoMoreInteractions(_listener.getMock());
                        return; 
                }
-               fail(); // should not get here. 
+               fail(); // should not get here.
                
        
        }
index ff37ccb9bfeb1e72aea95826c5fcf473f86b5a4a..8a060e8948a7f8620c9c2684e0dd8da49b8aa9b4 100644 (file)
 
 package org.wamblee.observer;
 
-import static org.easymock.EasyMock.createControl;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.createStrictMock;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
+import static org.mockito.Mockito.*; 
 
 import java.util.ArrayList;
 import java.util.List;
 
-import junit.framework.TestCase;
+import org.mockito.InOrder;
 
-import org.easymock.IMocksControl;
+import junit.framework.TestCase;
 
 /**
  * Test of the observer pattern implementation.
@@ -60,23 +56,24 @@ public class ObservableTest extends TestCase {
         * Tests subscription and notification of one subscriber.
         */
        public void testOneObserver() {
-               final Observer mockObserver = createStrictMock(Observer.class);
+               final Observer mockObserver = mock(Observer.class);
+               InOrder order = inOrder(mockObserver);
+               
                long subscription = _observable.subscribe(mockObserver);
 
                assertEquals(1, _observable.getObserverCount());
 
                final String message = "hallo";
-               mockObserver.send(_observed, message);
-               replay(mockObserver);
-
                _observable.send(message);
-               verify(mockObserver);
-
+               
+               order.verify(mockObserver).send(_observed, message);
+               verifyNoMoreInteractions(mockObserver);
+               
                _observable.unsubscribe(subscription);
                assertEquals(0, _observable.getObserverCount());
 
                _observable.send(message);
-
+               verifyNoMoreInteractions(mockObserver);
        }
 
        /**
@@ -87,12 +84,12 @@ public class ObservableTest extends TestCase {
        public void testManySubscribers() {
                final int nsubscribers = SUBSCRIBER_COUNT;
                final Observer[] mocks = new Observer[nsubscribers];
-
-               IMocksControl control = createControl();
+               final InOrder[] order = new InOrder[nsubscribers];
 
                List<Long> subscriptions = new ArrayList<Long>();
                for (int i = 0; i < nsubscribers; i++) {
-                       mocks[i] = control.createMock("mock" + i, Observer.class);
+                       mocks[i] = mock(Observer.class);
+                       order[i] = inOrder(mocks[i]);
                        long subscription = _observable.subscribe(mocks[i]);
                        assertTrue(subscriptions.add(subscription));
                }
@@ -101,13 +98,10 @@ public class ObservableTest extends TestCase {
 
                final String message = "hallo";
 
+               _observable.send(message);
                for (int i = 0; i < nsubscribers; i++) {
-                       mocks[i].send(_observed, message);
+                       order[i].verify(mocks[i]).send(_observed, message);
                }
-               control.replay();
-
-               _observable.send(message);
-               control.verify();
 
                for (int i = nsubscribers / 2; i < nsubscribers; i++) {
                        _observable.unsubscribe(subscriptions.get(i));
@@ -115,16 +109,16 @@ public class ObservableTest extends TestCase {
                assertEquals(nsubscribers - (nsubscribers - nsubscribers / 2),
                                _observable.getObserverCount());
 
-               control.reset();
                final String message2 = "blabla";
 
-               for (int i = 0; i < nsubscribers / 2; i++) {
-                       mocks[i].send(_observed, message2);
-               }
-               control.replay();
-
                _observable.send(message2);
-               control.verify();
+               for (int i = 0; i < nsubscribers / 2; i++) {
+                       order[i].verify(mocks[i]).send(_observed, message2);
+               }               
+               for (int i = nsubscribers/2; i < nsubscribers; i++) {
+                       verifyNoMoreInteractions(mocks[i]);
+               }               
+               
        }
 
        /**
@@ -133,9 +127,8 @@ public class ObservableTest extends TestCase {
         * 
         */
        public void testUnsubscribeWithWrongSubscription() {
-               Observer<Integer, String> observer = createMock(Observer.class);
-               replay(observer);
-               
+               Observer<Integer, String> observer = mock(Observer.class);
+       
                long subscription = _observable.subscribe(observer);
 
                assertEquals(1, _observable.getObserverCount());
diff --git a/support/general/src/test/java/org/wamblee/test/EasyMockMatchers.java b/support/general/src/test/java/org/wamblee/test/EasyMockMatchers.java
deleted file mode 100644 (file)
index ef9c5d0..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2008 the original author or authors.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- *      http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.wamblee.test;
-
-import org.easymock.IArgumentMatcher;
-import org.easymock.classextension.EasyMock;
-
-/**
- * Some general matchers for easy mock. 
- * 
- * @author Erik Brakkee
- */
-public class EasyMockMatchers {
-
-       public static class Any implements IArgumentMatcher {
-               public Any() {
-                       // Empty
-               }
-
-               @Override
-               public boolean matches(Object aArg0) {
-                       return true;
-               }
-
-               @Override
-               public void appendTo(StringBuffer aBuf) {
-                       aBuf.append("anyObject()");
-               }
-       }
-
-       /**
-        * Type-safe matcher to match any object of a given type. 
-        * @param <T>
-        * @param aType Type.
-        * @return Returns null.  
-        */
-       public static <T> T anyObject(Class<T> aType) {
-               EasyMock.reportMatcher(new Any());
-               return null;
-       }
-}
diff --git a/support/general/src/test/java/org/wamblee/test/ResettableMock.java b/support/general/src/test/java/org/wamblee/test/ResettableMock.java
new file mode 100644 (file)
index 0000000..47cc674
--- /dev/null
@@ -0,0 +1,95 @@
+/**
+ * 
+ */
+package org.wamblee.test;
+
+import static org.mockito.Mockito.*;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+
+/**
+ * Resettable mock is a utility to support reset functionality for mockito. 
+ * @author Erik Brakkee
+ *
+ * @param <T>
+ */
+public class ResettableMock<T> {
+
+       private static class MockitoInvocationHandler<T> implements
+                       InvocationHandler {
+
+               private Class<T> _class;
+               private T _mock;
+
+               public MockitoInvocationHandler(Class<T> aClass) {
+                       _class = aClass;
+                       _mock = mock(aClass);
+               }
+
+               public void reset() {
+                       _mock = mock(_class);
+               }
+
+               public T getMock() {
+                       return _mock;
+               }
+
+               @Override
+               public Object invoke(Object aProxy, Method aMethod, Object[] aArgs)
+                               throws Throwable {
+                       return aMethod.invoke(_mock, aArgs);
+               }
+       }
+
+       /**
+        * Invocation handler that delegates to the current mockito mock and allows
+        * creation of a new mock. 
+        */
+       private ResettableMock.MockitoInvocationHandler<T> _handler;
+       
+       /**
+        * Proxy object to be passed to tested classes. 
+        */
+       private T _proxy;
+
+       /**
+        * Constructs the resettable mock. 
+        * @param aType Type to mock. Must be an interface type. 
+        */
+       public ResettableMock(Class<T> aType) {
+               if ( !aType.isInterface()) { 
+                       throw new IllegalArgumentException("Class '" + aType.getName() + "' must be an interface");
+               }
+               _handler = new MockitoInvocationHandler(aType);
+               _proxy = (T) Proxy.newProxyInstance(aType.getClassLoader(),
+                               new Class[] { aType }, _handler);
+       }
+
+       /**
+        * Resets the mock effectively forgetting all previous interactions and verifications. 
+        */
+       public void reset() {
+               _handler.reset();
+       }
+
+       /**
+        * Gets the current mock object to pass to mockito calls. 
+        * 
+        * @return Mock object.
+        */
+       public T getMock() {
+               return _handler.getMock();
+       }
+
+       /**
+        * Returns the proxy that your tested classes will used.
+        * 
+        * @return Proxy object.
+        */
+       public T getProxy() {
+               return _proxy;
+       }
+
+}
\ No newline at end of file
index e61c023ca0e35ae66908b04259a0d99bee520a28..120548cb8b0063f30ab3e7c3a69e3a83b5d98ed5 100644 (file)
  */
 package org.wamblee.system.container;
 
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
+
 import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.List;
 
 import junit.framework.TestCase;
 
-import org.easymock.classextension.ConstructorArgs;
-import org.easymock.classextension.EasyMock;
-import org.easymock.classextension.IMocksControl;
 import org.wamblee.general.Pair;
 import org.wamblee.system.core.Component;
 import org.wamblee.system.core.DefaultProvidedInterface;
@@ -36,7 +36,6 @@ import org.wamblee.system.core.Scope;
 import org.wamblee.system.core.StringComponent;
 import org.wamblee.system.core.SystemAssemblyException;
 import org.wamblee.test.AssertionUtils;
-import org.wamblee.test.EasyMockMatchers;
 import org.wamblee.test.EventTracker;
 
 public class ContainerTest extends TestCase {
@@ -280,17 +279,14 @@ public class ContainerTest extends TestCase {
 
        public void testEnvironmentApplicationRollbackOnException()
                        throws Exception {
-               IMocksControl control = EasyMock.createStrictControl();
-
                Environment environment = new Environment(_tracker);
-               Application application = control.createMock(Application.class,
-                               new ConstructorArgs(Application.class.getConstructor()),
-                               Application.class.getDeclaredMethod("doStart", Scope.class));
-
-               application.doStart(EasyMockMatchers.anyObject(Scope.class));
-               EasyMock.expectLastCall().andThrow(new RuntimeException());
-               control.replay();
-
+               Application application = new Application() { 
+                       @Override
+                       public Object doStart(Scope aScope) {
+                               throw new RuntimeException();
+                       }
+               };
+               
                try {
                        Container container = new Container("root", new Component[] {
                                        environment, application }, new ProvidedInterface[0],
@@ -308,27 +304,22 @@ public class ContainerTest extends TestCase {
 
        public void testEnvironmentApplicationRollbackOnExceptionWithExceptionOnStop()
                        throws Exception {
-               IMocksControl control = EasyMock.createControl();
 
                Environment environment = new Environment(_tracker);
                // Application 1 will throw an exception while stopping.
-               Application application1 = control.createMock(Application.class,
-                               new ConstructorArgs(Application.class.getConstructor()),
-                               Application.class.getDeclaredMethod("doStop", Object.class));
-
-               application1.doStop(EasyMock.anyObject());
-               EasyMock.expectLastCall().andThrow(new RuntimeException());
+               Application application1 = new Application("app1")  {
+                       @Override
+                       public void doStop(Object aRuntime) {
+                               throw new RuntimeException();
+                       }
+               };
 
                // application 2 will throw an exception while starting
-               Application application2 = control.createMock(Application.class,
-                               new ConstructorArgs(Application.class
-                                               .getConstructor(String.class), "application2"),
-                               Application.class.getDeclaredMethod("doStart", Scope.class));
-
-               application2.doStart(EasyMockMatchers.anyObject(Scope.class));
-               EasyMock.expectLastCall().andThrow(new RuntimeException());
-
-               control.replay();
+               Application application2 = new Application("app2") {
+                       public Object doStart(Scope aScope) { 
+                               throw new RuntimeException();
+                       }
+               };
 
                try {
                        Container container = new Container("root", new Component[] {
index 7889c35723f25e62926c8530b4bc38f6eb6d6b87..55cae8964983a8e12efd2be53a7910651772a700 100644 (file)
@@ -19,9 +19,8 @@ import java.util.Arrays;
 
 import junit.framework.TestCase;
 
-import org.easymock.classextension.EasyMock;
-import org.easymock.classextension.IMocksControl;
-import static org.easymock.classextension.EasyMock.*;
+import static org.mockito.Mockito.*; 
+
 import org.wamblee.system.container.Application;
 import org.wamblee.system.core.Component;
 import org.wamblee.system.core.Environment;
@@ -48,14 +47,11 @@ public class CompositeEdgeFilterTest extends TestCase {
     }
     
     private void configureRestriction(EdgeFilter base, boolean aResult) {
-        base.isViolated( (Edge)EasyMock.anyObject());
-        EasyMock.expectLastCall().andReturn(aResult);
+       stub(base.isViolated((Edge)anyObject())).toReturn(aResult);
     }
     
     public void testOneRestriction() { 
-        IMocksControl control = EasyMock.createStrictControl();
-      
-        EdgeFilter base = control.createMock(EdgeFilter.class);
+        EdgeFilter base = mock(EdgeFilter.class);
         CompositeEdgeFilter composite = new CompositeEdgeFilter();
         composite.add(base);
         
@@ -63,59 +59,45 @@ public class CompositeEdgeFilterTest extends TestCase {
         
         configureRestriction(base, false);
         
-        control.replay();
         assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
                 _env, _env.getProvidedInterfaces().get(0))));
-        control.verify();
         
         // Second let the base return true and verify the result.
-        control.reset();
         configureRestriction(base, true);
         
-        control.replay();
         assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
                 _env, _env.getProvidedInterfaces().get(0))));
-        control.verify();
     }
 
    
     
     public void testTwoRestrictions() { 
-        IMocksControl control = EasyMock.createStrictControl();
-        
-        EdgeFilter base1 = control.createMock(EdgeFilter.class);
+        EdgeFilter base1 = mock(EdgeFilter.class);
         CompositeEdgeFilter composite = new CompositeEdgeFilter();
         composite.add(base1);
-        EdgeFilter base2 = control.createMock(EdgeFilter.class);
+        EdgeFilter base2 = mock(EdgeFilter.class);
         composite.add(base2);
         
         // 1. base1 not violated and base 2 not violated -> not violated. 
         
         configureRestriction(base1, false);
         configureRestriction(base2, false);
-        control.replay();
         assertFalse(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
                 _env, _env.getProvidedInterfaces().get(0))));
-        control.verify();
-        control.reset();
         
         // 2. base 1 not violated but base 2 violated -> violated
         configureRestriction(base1, false);
         configureRestriction(base2, true);
-        control.replay();
+       
         assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
                 _env, _env.getProvidedInterfaces().get(0))));
-        control.verify();
-        control.reset();
-        
+     
         // 3. base 1 violated -> violated and base 2 not called. 
         configureRestriction(base1, true);
         // base 2 should not be called.
-        control.replay();
+      
         assertTrue(composite.isViolated(createEdge(_app, _app.getRequiredInterfaces().get(0), 
                 _env, _env.getProvidedInterfaces().get(0))));
-        control.verify();
-        control.reset();
     }
     
 }
index 7a5a87971204255aa1c945af36b5b972fc826a04..675a06bd6c1c7247c713a9b1af79fc85b40afb27 100644 (file)
@@ -18,9 +18,10 @@ package org.wamblee.system.graph;
 import java.util.Arrays;
 import java.util.List;
 
-import org.easymock.classextension.EasyMock;
+import static org.mockito.Mockito.*;
 import org.wamblee.test.AssertionUtils;
 
+
 import junit.framework.TestCase;
 
 public class GraphTest extends TestCase {
@@ -156,12 +157,13 @@ public class GraphTest extends TestCase {
         graph.addNode(x);
         graph.addNode(y);
         graph.addEdge(e);
-        Visitor visitor = EasyMock.createMock(Visitor.class);
-        visitor.visitNode(x);
-        visitor.visitNode(y);
-        visitor.visitEdge(e);
-        EasyMock.replay(visitor);
+        Visitor visitor = mock(Visitor.class); 
+        
         graph.accept(visitor);
-        EasyMock.verify(visitor);
+        verify(visitor).visitNode(x);
+        verify(visitor).visitNode(y);
+        verify(visitor).visitEdge(e);
+        
+        verifyNoMoreInteractions(visitor);
     }
 }