Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2008,  Unitils.org
   *
   * 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.unitils.easymock;
 
 import static org.easymock.internal.MocksControl.MockType.DEFAULT;
 import static org.easymock.internal.MocksControl.MockType.NICE;
 import static org.unitils.reflectionassert.ReflectionComparatorMode.*;
 import static org.unitils.util.AnnotationUtils.getFieldsAnnotatedWith;
 import static org.unitils.util.AnnotationUtils.getMethodsAnnotatedWith;
 import static org.unitils.util.ModuleUtils.getAnnotationPropertyDefaults;
 import static org.unitils.util.ModuleUtils.getEnumValueReplaceDefault;
 import static org.unitils.util.ReflectionUtils.invokeMethod;
 import static org.unitils.util.ReflectionUtils.setFieldValue;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;

Module for testing with mock objects using EasyMock.

Mock creation is simplified by automatically inserting EasyMock generated mocks for fields annotated with the org.unitils.easymock.annotation.Mock annotation.

All methods annotated with org.unitils.easymock.annotation.AfterCreateMock will be called when a mock object was created. This provides you with a hook method for custom handling of the mock (e.g. adding the mocks to a service locator repository). A method can only be called if it has following signature void myMethod(Object mock, String name, Class type).

Mocks can also be created explicitly todo javadoc

Switching to the replay state and verifying expectations of all mocks (including the mocks created with the createMock() method can be done by calling the replay() and verify() methods.

Author(s):
Filip Neven
Tim Ducheyne
 
 public class EasyMockModule implements Module {
 
     /* Property key for configuring whether verify() is automatically called on every mock object after each test method execution */
     public static final String PROPKEY_AUTO_VERIFY_AFTER_TEST_ENABLED = "EasyMockModule.autoVerifyAfterTest.enabled";
 
     /* All created mocks controls */
     private List<MocksControlmocksControls;
 
     /* Map holding the default configuration of the mock annotations */
     private Map<Class<? extends Annotation>, Map<StringString>> defaultAnnotationPropertyValues;
 
     /* Indicates whether verify() is automatically called on every mock object after each test method execution */
     private boolean autoVerifyAfterTestEnabled;


    
Initializes the module
 
     @SuppressWarnings("unchecked")
 	public void init(Properties configuration) {
          = new ArrayList<MocksControl>();
          = getAnnotationPropertyDefaults(EasyMockModule.classconfigurationRegularMock.classMock.class);
          = PropertyUtils.getBoolean(configuration);
     }


    
No after initialization needed for this module
 
     public void afterInit() {
	}


Creates the listener for plugging in the behavior of this module into the test runs.

Returns:
the listener
    public TestListener getTestListener() {
        return new EasyMockTestListener();
    }


    
Creates an EasyMock mock object of the given type.

An instance of the mock control is stored, so that it can be set to the replay/verify state when replay() or verify() is called.

Parameters:
<T> the type of the mock
mockType the class type for the mock, not null
invocationOrder the order setting, not null
calls the calls setting, not null
Returns:
a mock for the given class or interface, not null
    public <T> T createRegularMock(Class<T> mockTypeInvocationOrder invocationOrderCalls calls) {
        // Get anotation arguments and replace default values if needed
        invocationOrder = getEnumValueReplaceDefault(RegularMock.class"invocationOrder"invocationOrder,
                );
        calls = getEnumValueReplaceDefault(RegularMock.class"calls"calls);
        MocksControl mocksControl;
        if (. == calls) {
            mocksControl = new MocksClassControl();
        } else {
            mocksControl = new MocksClassControl();
        }
        // Check order
        if (. == invocationOrder) {
            mocksControl.checkOrder(true);
        }
        .add(mocksControl);
        return mocksControl.createMock(mockType);
    }


    
todo javadoc

Creates an EasyMock mock instance of the given type (class/interface). The type of mock is determined as follows:

If returns is set to LENIENT, a nice mock is created, else a default mock is created If arguments is lenient a lenient control is create, else an EasyMock control is created If order is set to strict, invocation order checking is enabled

Parameters:
<T> the type of the mock
mockType the type of the mock, not null
invocationOrder the order setting, not null
calls the calls setting, not null
order todo
dates todo
defaults todo
Returns:
a mockcontrol for the given class or interface, not null
    public <T> T createMock(Class<T> mockTypeInvocationOrder invocationOrderCalls callsOrder orderDates datesDefaults defaults) {
        // Get anotation arguments and replace default values if needed
        invocationOrder = getEnumValueReplaceDefault(Mock.class"invocationOrder"invocationOrder);
        calls = getEnumValueReplaceDefault(Mock.class"calls"calls);
        order = getEnumValueReplaceDefault(Mock.class"order"order);
        dates = getEnumValueReplaceDefault(Mock.class"dates"dates);
        defaults = getEnumValueReplaceDefault(Mock.class"defaults"defaults);
        List<ReflectionComparatorModecomparatorModes = new ArrayList<ReflectionComparatorMode>();
        if (. == order) {
            comparatorModes.add();
        }
        if (. == dates) {
            comparatorModes.add();
        }
        if (. == defaults) {
            comparatorModes.add();
        }
        LenientMocksControl mocksControl;
        if (. == calls) {
            mocksControl = new LenientMocksControl(comparatorModes.toArray(new ReflectionComparatorMode[0]));
        } else {
            mocksControl = new LenientMocksControl(comparatorModes.toArray(new ReflectionComparatorMode[0]));
        }
        // Check order
        if (. == invocationOrder) {
            mocksControl.checkOrder(true);
        }
        .add(mocksControl);
        return mocksControl.createMock(mockType);
    }


    
Replays all mock controls.
    public void replay() {
        for (MocksControl mocksControl : ) {
            mocksControl.replay();
        }
    }


    
    public void verify() {
        for (MocksControl mocksControl : ) {
            if (!(mocksControl.getState() instanceof ReplayState)) {
                mocksControl.replay();
            }
            mocksControl.verify();
        }
    }


    
Creates and sets a mock for all org.unitils.easymock.annotation.RegularMock annotated fields.

The todo javadoc method is called for creating the mocks. Ones the mock is created, all methods annotated with org.unitils.easymock.annotation.AfterCreateMock will be called passing the created mock.

Parameters:
testObject the test, not null
    protected void createAndInjectRegularMocksIntoTest(Object testObject) {
        Set<FieldmockFields = getFieldsAnnotatedWith(testObject.getClass(), RegularMock.class);
        for (Field mockField : mockFields) {
            Class<?> mockType = mockField.getType();
            RegularMock regularMockAnnotation = mockField.getAnnotation(RegularMock.class);
            Object mockObject = createRegularMock(mockTyperegularMockAnnotation.invocationOrder(), regularMockAnnotation.calls());
            setFieldValue(testObjectmockFieldmockObject);
            callAfterCreateMockMethods(testObjectmockObjectmockField.getName(), mockType);
        }
    }
    //todo javadoc
    protected void createAndInjectMocksIntoTest(Object testObject) {
    	Set<FieldmockFields = getFieldsAnnotatedWith(testObject.getClass(), Mock.class);
        for (Field mockField : mockFields) {
            Class<?> mockType = mockField.getType();
            Mock mockAnnotation = mockField.getAnnotation(Mock.class);
            Object mockObject = createMock(mockTypemockAnnotation.invocationOrder(), mockAnnotation.calls(), mockAnnotation.order(), mockAnnotation.dates(), mockAnnotation.defaults());
            setFieldValue(testObjectmockFieldmockObject);
            callAfterCreateMockMethods(testObjectmockObjectmockField.getName(), mockType);
        }
    }


    
Calls all org.unitils.easymock.annotation.AfterCreateMock annotated methods on the test, passing the given mock. These annotated methods must have following signature void myMethod(Object mock, String name, Class type). If this is not the case, a runtime exception is called.

Parameters:
testObject the test, not null
mockObject the mock, not null
name the field(=mock) name, not null
type the field(=mock) type
    protected void callAfterCreateMockMethods(Object testObjectObject mockObjectString nameClass<?> type) {
    	Set<Methodmethods = getMethodsAnnotatedWith(testObject.getClass(), AfterCreateMock.class);
        for (Method method : methods) {
            try {
                invokeMethod(testObjectmethodmockObjectnametype);
            } catch (InvocationTargetException e) {
                throw new UnitilsException("An exception occurred while invoking an after create mock method."e);
            } catch (Exception e) {
                throw new UnitilsException("Unable to invoke after create mock method. Ensure that this method has following signature: " +
                        "void myMethod(Object mock, String name, Class type)"e);
            }
        }
    }


    
Test listener that handles the mock creation and injection.
    protected class EasyMockTestListener extends TestListener {

        
Before the test is executed this calls EasyMockModule.createAndInjectRegularMocksIntoTest(java.lang.Object) to create and inject all mocks on the class.
        @Override
        public void beforeTestSetUp(Object testObjectMethod testMethod) {
            // Clear all previously created mocks controls
            .clear();
            createAndInjectRegularMocksIntoTest(testObject);
            createAndInjectMocksIntoTest(testObject);
        }

        
After each test is executed this calls EasyMockModule.verify() to verify the recorded behavior of all created mocks.
        @Override
        public void afterTestMethod(Object testObjectMethod testMethodThrowable throwable) {
            if ( && throwable == null) {
                verify();
            }
        }
    }
New to GrepCode? Check out our FAQ X