Update of /cvsroot/mocklib/mocklib3/input/javasrc/biz/xsoftware/mock
In directory 23jxhf1.ch3.sourceforge.com:/tmp/cvs-serv26624/input/javasrc/biz/xsoftware/mock
Modified Files:
MockObjectFactory.java
Log Message:
- Added to factory method that will create a MockObject and inject it into an object
- Adding Apache License header
Index: MockObjectFactory.java
===================================================================
RCS file: /cvsroot/mocklib/mocklib3/input/javasrc/biz/xsoftware/mock/MockObjectFactory.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -C2 -d -r1.7 -r1.8
*** MockObjectFactory.java 23 May 2008 19:06:06 -0000 1.7
--- MockObjectFactory.java 11 Feb 2009 18:33:12 -0000 1.8
***************
*** 1,4 ****
--- 1,6 ----
package biz.xsoftware.mock;
+ import java.lang.reflect.Field;
+
/**
***************
*** 102,105 ****
--- 104,145 ----
return factory.createMockImpl("[" + id + "]", interfaces);
}
+
+ /**
+ * Creates and injects a MockObject created with the given classToMock and
+ * injects it into the given field name from the provided object instance.
+ * <p>
+ * This method uses reflection to set a, sometimes private, field inside the
+ * provided objToInjectTo. This is usefull when testing in environments that
+ * use injection that doesn't require a setter method like EJB3 or SCA.
+ *
+ * Note: In order for this method to work Java security cannot be enabled
+ *
+ * @param objToInjectTo
+ * The object instance to inject the create {@link MockObject} into
+ * @param fieldToInjectTo
+ * The field name in the objToInjectTo class to be set with the
+ * created {@link MockObject}
+ * @param classesToMock
+ * The interface(s) to create the {@link MockObject} with
+ */
+ public static final MockObject injectMock(Object objToInjectTo, String fieldToInjectTo,
+ Class<?> ... classesToMock) {
+ try {
+ MockObject mock = MockObjectFactory.createMock(classesToMock);
+ Field f = objToInjectTo.getClass().getDeclaredField(fieldToInjectTo);
+ f.setAccessible(true);
+ f.set(objToInjectTo, mock);
+
+ return mock;
+ } catch (SecurityException e) {
+ throw new RuntimeException(e);
+ } catch (NoSuchFieldException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalArgumentException e) {
+ throw new RuntimeException(e);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
private static void loadFactory() {
|