[SPR-8633] Introduced generic invokeMethod() in ReflectionTestUtils.

This commit is contained in:
Sam Brannen
2011-08-24 17:26:59 +00:00
parent 72da569aa3
commit 4d99ddba8a
4 changed files with 337 additions and 182 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2009 the original author or authors.
* Copyright 2002-2011 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.
@@ -22,28 +22,32 @@ import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.MethodInvoker;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
/**
* <p>
* ReflectionTestUtils is a collection of reflection-based utility methods for
* use in unit and integration testing scenarios.
* </p>
* <p>
* There are often situations in which it would be beneficial to be able to set
* a non-<code>public</code> field or invoke a non-<code>public</code> setter
* method when testing code involving, for example:
* </p>
* {@code ReflectionTestUtils} is a collection of reflection-based utility
* methods for use in unit and integration testing scenarios.
*
* <p>There are often times when it would be beneficial to be able to set a
* non-{@code public} field, invoke a non-{@code public} setter method, or
* invoke a non-{@code public} <em>configuration</em> or <em>lifecycle</em>
* callback method when testing code involving, for example:
*
* <ul>
* <li>ORM frameworks such as JPA and Hibernate which condone the usage of
* <code>private</code> or <code>protected</code> field access as opposed to
* <code>public</code> setter methods for properties in a domain entity.</li>
* {@code private} or {@code protected} field access as opposed to
* {@code public} setter methods for properties in a domain entity.</li>
* <li>Spring's support for annotations such as
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired} and
* {@link javax.annotation.Resource @Resource} which provides dependency
* injection for <code>private</code> or <code>protected</code> fields, setter
* methods, and configuration methods.</li>
* injection for {@code private} or {@code protected} fields, setter methods,
* and configuration methods.</li>
* <li>Use of annotations such as {@link javax.annotation.PostConstruct @PostConstruct}
* and {@link javax.annotation.PreDestroy @PreDestroy} for lifecycle callback
* methods.</li>
* </ul>
*
* @author Sam Brannen
@@ -61,14 +65,13 @@ public class ReflectionTestUtils {
/**
* Set the {@link Field field} with the given <code>name</code> on the
* provided {@link Object target object} to the supplied <code>value</code>.
* <p>
* This method traverses the class hierarchy in search of the desired field.
* In addition, an attempt will be made to make non-<code>public</code>
* fields <em>accessible</em>, thus allowing one to set
* <code>protected</code>, <code>private</code>, and
* <em>package-private</em> fields.
* Set the {@link Field field} with the given {@code name} on the provided
* {@link Object target object} to the supplied {@code value}.
*
* <p>This method traverses the class hierarchy in search of the desired field.
* In addition, an attempt will be made to make non-{@code public} fields
* <em>accessible</em>, thus allowing one to set {@code protected},
* {@code private}, and <em>package-private</em> fields.
*
* @param target the target object on which to set the field
* @param name the name of the field to set
@@ -82,19 +85,18 @@ public class ReflectionTestUtils {
}
/**
* Set the {@link Field field} with the given <code>name</code> on the
* provided {@link Object target object} to the supplied <code>value</code>.
* <p>
* This method traverses the class hierarchy in search of the desired field.
* In addition, an attempt will be made to make non-<code>public</code>
* fields <em>accessible</em>, thus allowing one to set
* <code>protected</code>, <code>private</code>, and
* <em>package-private</em> fields.
* Set the {@link Field field} with the given {@code name} on the provided
* {@link Object target object} to the supplied {@code value}.
*
* <p>This method traverses the class hierarchy in search of the desired
* field. In addition, an attempt will be made to make non-{@code public}
* fields <em>accessible</em>, thus allowing one to set {@code protected},
* {@code private}, and <em>package-private</em> fields.
*
* @param target the target object on which to set the field
* @param name the name of the field to set
* @param value the value to set
* @param type the type of the field (may be <code>null</code>)
* @param type the type of the field (may be {@code null})
* @see ReflectionUtils#findField(Class, String, Class)
* @see ReflectionUtils#makeAccessible(Field)
* @see ReflectionUtils#setField(Field, Object, Object)
@@ -102,9 +104,7 @@ public class ReflectionTestUtils {
public static void setField(Object target, String name, Object value, Class<?> type) {
Assert.notNull(target, "Target object must not be null");
Field field = ReflectionUtils.findField(target.getClass(), name, type);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + name + "] on target [" + target + "]");
}
Assert.notNull(field, "Could not find field [" + name + "] on target [" + target + "]");
if (logger.isDebugEnabled()) {
logger.debug("Setting field [" + name + "] on target [" + target + "]");
@@ -114,14 +114,12 @@ public class ReflectionTestUtils {
}
/**
* Get the field with the given <code>name</code> from the provided target
* object.
* <p>
* This method traverses the class hierarchy in search of the desired field.
* In addition, an attempt will be made to make non-<code>public</code>
* fields <em>accessible</em>, thus allowing one to get
* <code>protected</code>, <code>private</code>, and
* <em>package-private</em> fields.
* Get the field with the given {@code name} from the provided target object.
*
* <p>This method traverses the class hierarchy in search of the desired
* field. In addition, an attempt will be made to make non-{@code public}
* fields <em>accessible</em>, thus allowing one to get {@code protected},
* {@code private}, and <em>package-private</em> fields.
*
* @param target the target object on which to set the field
* @param name the name of the field to get
@@ -133,9 +131,7 @@ public class ReflectionTestUtils {
public static Object getField(Object target, String name) {
Assert.notNull(target, "Target object must not be null");
Field field = ReflectionUtils.findField(target.getClass(), name);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" + name + "] on target [" + target + "]");
}
Assert.notNull(field, "Could not find field [" + name + "] on target [" + target + "]");
if (logger.isDebugEnabled()) {
logger.debug("Getting field [" + name + "] from target [" + target + "]");
@@ -145,17 +141,16 @@ public class ReflectionTestUtils {
}
/**
* Invoke the setter method with the given <code>name</code> on the supplied
* target object with the supplied <code>value</code>.
* <p>
* This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-
* <code>public</code> methods <em>accessible</em>, thus allowing one to
* invoke <code>protected</code>, <code>private</code>, and
* <em>package-private</em> setter methods.
* <p>
* In addition, this method supports JavaBean-style <em>property</em> names.
* For example, if you wish to set the <code>name</code> property on the
* Invoke the setter method with the given {@code name} on the supplied
* target object with the supplied {@code value}.
*
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> setter methods.
*
* <p>In addition, this method supports JavaBean-style <em>property</em>
* names. For example, if you wish to set the {@code name} property on the
* target object, you may pass either &quot;name&quot; or
* &quot;setName&quot; as the method name.
*
@@ -173,17 +168,16 @@ public class ReflectionTestUtils {
}
/**
* Invoke the setter method with the given <code>name</code> on the supplied
* target object with the supplied <code>value</code>.
* <p>
* This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-
* <code>public</code> methods <em>accessible</em>, thus allowing one to
* invoke <code>protected</code>, <code>private</code>, and
* <em>package-private</em> setter methods.
* <p>
* In addition, this method supports JavaBean-style <em>property</em> names.
* For example, if you wish to set the <code>name</code> property on the
* Invoke the setter method with the given {@code name} on the supplied
* target object with the supplied {@code value}.
*
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> setter methods.
*
* <p>In addition, this method supports JavaBean-style <em>property</em>
* names. For example, if you wish to set the {@code name} property on the
* target object, you may pass either &quot;name&quot; or
* &quot;setName&quot; as the method name.
*
@@ -199,7 +193,7 @@ public class ReflectionTestUtils {
*/
public static void invokeSetterMethod(Object target, String name, Object value, Class<?> type) {
Assert.notNull(target, "Target object must not be null");
Assert.notNull(name, "Method name must not be empty");
Assert.hasText(name, "Method name must not be empty");
Class<?>[] paramTypes = (type != null ? new Class<?>[] { type } : null);
String setterMethodName = name;
@@ -211,10 +205,8 @@ public class ReflectionTestUtils {
setterMethodName = name;
method = ReflectionUtils.findMethod(target.getClass(), setterMethodName, paramTypes);
}
if (method == null) {
throw new IllegalArgumentException("Could not find setter method [" + setterMethodName + "] on target ["
+ target + "] with parameter type [" + type + "]");
}
Assert.notNull(method, "Could not find setter method [" + setterMethodName + "] on target [" + target
+ "] with parameter type [" + type + "]");
if (logger.isDebugEnabled()) {
logger.debug("Invoking setter method [" + setterMethodName + "] on target [" + target + "]");
@@ -224,17 +216,16 @@ public class ReflectionTestUtils {
}
/**
* Invoke the getter method with the given <code>name</code> on the supplied
* target object with the supplied <code>value</code>.
* <p>
* This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-
* <code>public</code> methods <em>accessible</em>, thus allowing one to
* invoke <code>protected</code>, <code>private</code>, and
* <em>package-private</em> getter methods.
* <p>
* In addition, this method supports JavaBean-style <em>property</em> names.
* For example, if you wish to get the <code>name</code> property on the
* Invoke the getter method with the given {@code name} on the supplied
* target object with the supplied {@code value}.
*
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> getter methods.
*
* <p>In addition, this method supports JavaBean-style <em>property</em>
* names. For example, if you wish to get the {@code name} property on the
* target object, you may pass either &quot;name&quot; or
* &quot;getName&quot; as the method name.
*
@@ -249,7 +240,7 @@ public class ReflectionTestUtils {
*/
public static Object invokeGetterMethod(Object target, String name) {
Assert.notNull(target, "Target object must not be null");
Assert.notNull(name, "Method name must not be empty");
Assert.hasText(name, "Method name must not be empty");
String getterMethodName = name;
if (!name.startsWith(GETTER_PREFIX)) {
@@ -260,10 +251,7 @@ public class ReflectionTestUtils {
getterMethodName = name;
method = ReflectionUtils.findMethod(target.getClass(), getterMethodName);
}
if (method == null) {
throw new IllegalArgumentException("Could not find getter method [" + getterMethodName + "] on target ["
+ target + "]");
}
Assert.notNull(method, "Could not find getter method [" + getterMethodName + "] on target [" + target + "]");
if (logger.isDebugEnabled()) {
logger.debug("Invoking getter method [" + getterMethodName + "] on target [" + target + "]");
@@ -272,4 +260,48 @@ public class ReflectionTestUtils {
return ReflectionUtils.invokeMethod(method, target);
}
/**
* Invoke the method with the given {@code name} on the supplied target
* object with the supplied arguments.
*
* <p>This method traverses the class hierarchy in search of the desired
* method. In addition, an attempt will be made to make non-{@code public}
* methods <em>accessible</em>, thus allowing one to invoke {@code protected},
* {@code private}, and <em>package-private</em> methods.
*
* @param target the target object on which to invoke the specified method
* @param name the name of the method to invoke
* @param args the arguments to provide to the method
* @return the invocation result, if any
* @see MethodInvoker
* @see ReflectionUtils#makeAccessible(Method)
* @see ReflectionUtils#invokeMethod(Method, Object, Object[])
* @see ReflectionUtils#handleReflectionException(Exception)
*/
@SuppressWarnings("unchecked")
public static <T> T invokeMethod(Object target, String name, Object... args) {
Assert.notNull(target, "Target object must not be null");
Assert.hasText(name, "Method name must not be empty");
try {
MethodInvoker methodInvoker = new MethodInvoker();
methodInvoker.setTargetObject(target);
methodInvoker.setTargetMethod(name);
methodInvoker.setArguments(args);
methodInvoker.prepare();
if (logger.isDebugEnabled()) {
logger.debug("Invoking method [" + name + "] on target [" + target + "] with arguments ["
+ ObjectUtils.nullSafeToString(args) + "]");
}
return (T) methodInvoker.invoke();
}
catch (Exception e) {
ReflectionUtils.handleReflectionException(e);
}
throw new IllegalStateException("Should never get here");
}
}

View File

@@ -16,69 +16,80 @@
package org.springframework.test.util;
import junit.framework.TestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.springframework.test.util.ReflectionTestUtils.getField;
import static org.springframework.test.util.ReflectionTestUtils.invokeGetterMethod;
import static org.springframework.test.util.ReflectionTestUtils.invokeMethod;
import static org.springframework.test.util.ReflectionTestUtils.invokeSetterMethod;
import static org.springframework.test.util.ReflectionTestUtils.setField;
import org.junit.Test;
import org.springframework.test.AssertThrows;
import org.springframework.test.util.subpackage.Component;
import org.springframework.test.util.subpackage.Person;
/**
* JUnit 3.8 based unit tests for {@link ReflectionTestUtils}.
* Unit tests for {@link ReflectionTestUtils}.
*
* @author Sam Brannen
* @author Juergen Hoeller
*/
@SuppressWarnings("deprecation")
public class ReflectionTestUtilsTests extends TestCase {
public class ReflectionTestUtilsTests {
protected static final Float PI = new Float((float) 22 / 7);
private static final Float PI = new Float((float) 22 / 7);
private final Person person = new Person();
private final Component component = new Component();
public void testSetField() throws Exception {
final Person person = new Person();
@Test
public void setAndGetFields() throws Exception {
// ---------------------------------------------------------------------
// Standard
ReflectionTestUtils.setField(person, "id", new Long(99), long.class);
ReflectionTestUtils.setField(person, "name", "Tom");
ReflectionTestUtils.setField(person, "age", new Integer(42));
ReflectionTestUtils.setField(person, "eyeColor", "blue", String.class);
ReflectionTestUtils.setField(person, "likesPets", Boolean.TRUE);
ReflectionTestUtils.setField(person, "favoriteNumber", PI, Number.class);
setField(person, "id", new Long(99), long.class);
setField(person, "name", "Tom");
setField(person, "age", new Integer(42));
setField(person, "eyeColor", "blue", String.class);
setField(person, "likesPets", Boolean.TRUE);
setField(person, "favoriteNumber", PI, Number.class);
assertEquals("Verifying that the person's ID (private field in a superclass) was set.", 99, person.getId());
assertEquals("Verifying that the person's name (protected field) was set.", "Tom", person.getName());
assertEquals("Verifying that the person's age (private field) was set.", 42, person.getAge());
assertEquals("Verifying that the person's eye color (package private field) was set.", "blue",
person.getEyeColor());
assertEquals("Verifying that the person's 'likes pets' flag (package private boolean field) was set.", true,
person.likesPets());
assertEquals("Verifying that the person's 'favorite number' (package field) was set.", PI,
person.getFavoriteNumber());
assertEquals("ID (private field in a superclass)", 99, person.getId());
assertEquals("name (protected field)", "Tom", person.getName());
assertEquals("age (private field)", 42, person.getAge());
assertEquals("eye color (package private field)", "blue", person.getEyeColor());
assertEquals("'likes pets' flag (package private boolean field)", true, person.likesPets());
assertEquals("'favorite number' (package field)", PI, person.getFavoriteNumber());
assertEquals(new Long(99), ReflectionTestUtils.getField(person, "id"));
assertEquals("Tom", ReflectionTestUtils.getField(person, "name"));
assertEquals(new Integer(42), ReflectionTestUtils.getField(person, "age"));
assertEquals("blue", ReflectionTestUtils.getField(person, "eyeColor"));
assertEquals(Boolean.TRUE, ReflectionTestUtils.getField(person, "likesPets"));
assertEquals(PI, ReflectionTestUtils.getField(person, "favoriteNumber"));
assertEquals(new Long(99), getField(person, "id"));
assertEquals("Tom", getField(person, "name"));
assertEquals(new Integer(42), getField(person, "age"));
assertEquals("blue", getField(person, "eyeColor"));
assertEquals(Boolean.TRUE, getField(person, "likesPets"));
assertEquals(PI, getField(person, "favoriteNumber"));
// ---------------------------------------------------------------------
// Null - non-primitives
ReflectionTestUtils.setField(person, "name", null, String.class);
ReflectionTestUtils.setField(person, "eyeColor", null, String.class);
ReflectionTestUtils.setField(person, "favoriteNumber", null, Number.class);
setField(person, "name", null, String.class);
setField(person, "eyeColor", null, String.class);
setField(person, "favoriteNumber", null, Number.class);
assertNull("Verifying that the person's name (protected field) was set.", person.getName());
assertNull("Verifying that the person's eye color (package private field) was set.", person.getEyeColor());
assertNull("Verifying that the person's 'favorite number' (package field) was set.", person.getFavoriteNumber());
assertNull("name (protected field)", person.getName());
assertNull("eye color (package private field)", person.getEyeColor());
assertNull("'favorite number' (package field)", person.getFavoriteNumber());
// ---------------------------------------------------------------------
// Null - primitives
new AssertThrows(IllegalArgumentException.class,
"Calling setField() with NULL for a primitive type should throw an IllegalArgumentException.") {
public void test() throws Exception {
ReflectionTestUtils.setField(person, "id", null, long.class);
setField(person, "id", null, long.class);
}
}.runTest();
@@ -86,7 +97,7 @@ public class ReflectionTestUtilsTests extends TestCase {
"Calling setField() with NULL for a primitive type should throw an IllegalArgumentException.") {
public void test() throws Exception {
ReflectionTestUtils.setField(person, "age", null, int.class);
setField(person, "age", null, int.class);
}
}.runTest();
@@ -94,102 +105,145 @@ public class ReflectionTestUtilsTests extends TestCase {
"Calling setField() with NULL for a primitive type should throw an IllegalArgumentException.") {
public void test() throws Exception {
ReflectionTestUtils.setField(person, "likesPets", null, boolean.class);
setField(person, "likesPets", null, boolean.class);
}
}.runTest();
}
public void testInvokeSetterMethod() throws Exception {
final Person person = new Person();
@Test
public void invokeSetterAndMethods() throws Exception {
// ---------------------------------------------------------------------
// Standard - properties
ReflectionTestUtils.invokeSetterMethod(person, "id", new Long(99), long.class);
ReflectionTestUtils.invokeSetterMethod(person, "name", "Tom");
ReflectionTestUtils.invokeSetterMethod(person, "age", new Integer(42));
ReflectionTestUtils.invokeSetterMethod(person, "eyeColor", "blue", String.class);
ReflectionTestUtils.invokeSetterMethod(person, "likesPets", Boolean.TRUE);
ReflectionTestUtils.invokeSetterMethod(person, "favoriteNumber", PI, Number.class);
invokeSetterMethod(person, "id", new Long(99), long.class);
invokeSetterMethod(person, "name", "Tom");
invokeSetterMethod(person, "age", new Integer(42));
invokeSetterMethod(person, "eyeColor", "blue", String.class);
invokeSetterMethod(person, "likesPets", Boolean.TRUE);
invokeSetterMethod(person, "favoriteNumber", PI, Number.class);
assertEquals("Verifying that the person's ID (protected method in a superclass) was set.", 99, person.getId());
assertEquals("Verifying that the person's name (private method) was set.", "Tom", person.getName());
assertEquals("Verifying that the person's age (protected method) was set.", 42, person.getAge());
assertEquals("Verifying that the person's eye color (package private method) was set.", "blue",
person.getEyeColor());
assertEquals("Verifying that the person's 'likes pets' flag (protected method for a boolean) was set.", true,
person.likesPets());
assertEquals("Verifying that the person's 'favorite number' (protected method for a Number) was set.", PI,
person.getFavoriteNumber());
assertEquals("ID (protected method in a superclass)", 99, person.getId());
assertEquals("name (private method)", "Tom", person.getName());
assertEquals("age (protected method)", 42, person.getAge());
assertEquals("eye color (package private method)", "blue", person.getEyeColor());
assertEquals("'likes pets' flag (protected method for a boolean)", true, person.likesPets());
assertEquals("'favorite number' (protected method for a Number)", PI, person.getFavoriteNumber());
assertEquals(new Long(99), ReflectionTestUtils.invokeGetterMethod(person, "id"));
assertEquals("Tom", ReflectionTestUtils.invokeGetterMethod(person, "name"));
assertEquals(new Integer(42), ReflectionTestUtils.invokeGetterMethod(person, "age"));
assertEquals("blue", ReflectionTestUtils.invokeGetterMethod(person, "eyeColor"));
assertEquals(Boolean.TRUE, ReflectionTestUtils.invokeGetterMethod(person, "likesPets"));
assertEquals(PI, ReflectionTestUtils.invokeGetterMethod(person, "favoriteNumber"));
assertEquals(new Long(99), invokeGetterMethod(person, "id"));
assertEquals("Tom", invokeGetterMethod(person, "name"));
assertEquals(new Integer(42), invokeGetterMethod(person, "age"));
assertEquals("blue", invokeGetterMethod(person, "eyeColor"));
assertEquals(Boolean.TRUE, invokeGetterMethod(person, "likesPets"));
assertEquals(PI, invokeGetterMethod(person, "favoriteNumber"));
// ---------------------------------------------------------------------
// Standard - setter methods
ReflectionTestUtils.invokeSetterMethod(person, "setId", new Long(1), long.class);
ReflectionTestUtils.invokeSetterMethod(person, "setName", "Jerry", String.class);
ReflectionTestUtils.invokeSetterMethod(person, "setAge", new Integer(33), int.class);
ReflectionTestUtils.invokeSetterMethod(person, "setEyeColor", "green", String.class);
ReflectionTestUtils.invokeSetterMethod(person, "setLikesPets", Boolean.FALSE, boolean.class);
ReflectionTestUtils.invokeSetterMethod(person, "setFavoriteNumber", new Integer(42), Number.class);
invokeSetterMethod(person, "setId", new Long(1), long.class);
invokeSetterMethod(person, "setName", "Jerry", String.class);
invokeSetterMethod(person, "setAge", new Integer(33), int.class);
invokeSetterMethod(person, "setEyeColor", "green", String.class);
invokeSetterMethod(person, "setLikesPets", Boolean.FALSE, boolean.class);
invokeSetterMethod(person, "setFavoriteNumber", new Integer(42), Number.class);
assertEquals("Verifying that the person's ID (protected method in a superclass) was set.", 1, person.getId());
assertEquals("Verifying that the person's name (private method) was set.", "Jerry", person.getName());
assertEquals("Verifying that the person's age (protected method) was set.", 33, person.getAge());
assertEquals("Verifying that the person's eye color (package private method) was set.", "green",
person.getEyeColor());
assertEquals("Verifying that the person's 'likes pets' flag (protected method for a boolean) was set.", false,
person.likesPets());
assertEquals("Verifying that the person's 'favorite number' (protected method for a Number) was set.",
new Integer(42), person.getFavoriteNumber());
assertEquals("ID (protected method in a superclass)", 1, person.getId());
assertEquals("name (private method)", "Jerry", person.getName());
assertEquals("age (protected method)", 33, person.getAge());
assertEquals("eye color (package private method)", "green", person.getEyeColor());
assertEquals("'likes pets' flag (protected method for a boolean)", false, person.likesPets());
assertEquals("'favorite number' (protected method for a Number)", new Integer(42), person.getFavoriteNumber());
assertEquals(new Long(1), ReflectionTestUtils.invokeGetterMethod(person, "getId"));
assertEquals("Jerry", ReflectionTestUtils.invokeGetterMethod(person, "getName"));
assertEquals(new Integer(33), ReflectionTestUtils.invokeGetterMethod(person, "getAge"));
assertEquals("green", ReflectionTestUtils.invokeGetterMethod(person, "getEyeColor"));
assertEquals(Boolean.FALSE, ReflectionTestUtils.invokeGetterMethod(person, "likesPets"));
assertEquals(new Integer(42), ReflectionTestUtils.invokeGetterMethod(person, "getFavoriteNumber"));
assertEquals(new Long(1), invokeGetterMethod(person, "getId"));
assertEquals("Jerry", invokeGetterMethod(person, "getName"));
assertEquals(new Integer(33), invokeGetterMethod(person, "getAge"));
assertEquals("green", invokeGetterMethod(person, "getEyeColor"));
assertEquals(Boolean.FALSE, invokeGetterMethod(person, "likesPets"));
assertEquals(new Integer(42), invokeGetterMethod(person, "getFavoriteNumber"));
// ---------------------------------------------------------------------
// Null - non-primitives
ReflectionTestUtils.invokeSetterMethod(person, "name", null, String.class);
ReflectionTestUtils.invokeSetterMethod(person, "eyeColor", null, String.class);
ReflectionTestUtils.invokeSetterMethod(person, "favoriteNumber", null, Number.class);
invokeSetterMethod(person, "name", null, String.class);
invokeSetterMethod(person, "eyeColor", null, String.class);
invokeSetterMethod(person, "favoriteNumber", null, Number.class);
assertNull("Verifying that the person's name (private method) was set.", person.getName());
assertNull("Verifying that the person's eye color (package private method) was set.", person.getEyeColor());
assertNull("Verifying that the person's 'favorite number' (protected method for a Number) was set.",
person.getFavoriteNumber());
assertNull("name (private method)", person.getName());
assertNull("eye color (package private method)", person.getEyeColor());
assertNull("'favorite number' (protected method for a Number)", person.getFavoriteNumber());
// ---------------------------------------------------------------------
// Null - primitives
new AssertThrows(RuntimeException.class,
new AssertThrows(IllegalArgumentException.class,
"Calling invokeSetterMethod() with NULL for a primitive type should throw an IllegalArgumentException.") {
public void test() throws Exception {
ReflectionTestUtils.invokeSetterMethod(person, "id", null, long.class);
invokeSetterMethod(person, "id", null, long.class);
}
}.runTest();
new AssertThrows(RuntimeException.class,
new AssertThrows(IllegalArgumentException.class,
"Calling invokeSetterMethod() with NULL for a primitive type should throw an IllegalArgumentException.") {
public void test() throws Exception {
ReflectionTestUtils.invokeSetterMethod(person, "age", null, int.class);
invokeSetterMethod(person, "age", null, int.class);
}
}.runTest();
new AssertThrows(RuntimeException.class,
new AssertThrows(IllegalArgumentException.class,
"Calling invokeSetterMethod() with NULL for a primitive type should throw an IllegalArgumentException.") {
public void test() throws Exception {
ReflectionTestUtils.invokeSetterMethod(person, "likesPets", null, boolean.class);
invokeSetterMethod(person, "likesPets", null, boolean.class);
}
}.runTest();
}
@Test
public void invokeMethodWithReturnValueWithAutoboxingAndUnboxing() {
int sum = invokeMethod(component, "add", 1, 2);
assertEquals("add(1, 2)", 3, sum);
}
@Test
public void invokeMethodsSimulatingLifecycleEvents() {
assertNull("number", component.getNumber());
assertNull("text", component.getText());
// Simulate autowiring a configuration method
invokeMethod(component, "configure", new Integer(42), "enigma");
assertEquals("number should have been configured", new Integer(42), component.getNumber());
assertEquals("text should have been configured", "enigma", component.getText());
// Simulate @PostConstruct life-cycle event
invokeMethod(component, "init");
// assertions in init() should succeed
// Simulate @PreDestroy life-cycle event
invokeMethod(component, "destroy");
assertNull("number", component.getNumber());
assertNull("text", component.getText());
}
@Test(expected = IllegalStateException.class)
public void invokeMethodWithIncompatibleArgumentTypes() {
invokeMethod(component, "add", "foo", 2.0);
}
@Test(expected = IllegalStateException.class)
public void invokeInitMethodBeforeAutowiring() {
invokeMethod(component, "init");
}
@Test(expected = IllegalStateException.class)
public void invokeMethodWithTooFewArguments() {
invokeMethod(component, "configure", new Integer(42));
}
@Test(expected = IllegalStateException.class)
public void invokeMethodWithTooManyArguments() {
invokeMethod(component, "configure", new Integer(42), "enigma", "baz", "quux");
}
}

View File

@@ -0,0 +1,69 @@
/*
* Copyright 2002-2011 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.springframework.test.util.subpackage;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Simple POJO representing a <em>component</em>; intended for use in
* unit tests.
*
* @author Sam Brannen
* @since 3.1
*/
public class Component {
private Integer number;
private String text;
public Integer getNumber() {
return this.number;
}
public String getText() {
return this.text;
}
@Autowired
protected void configure(Integer number, String text) {
this.number = number;
this.text = text;
}
@PostConstruct
protected void init() {
Assert.state(number != null, "number must not be null");
Assert.state(StringUtils.hasText(text), "text must not be empty");
}
@PreDestroy
protected void destroy() {
this.number = null;
this.text = null;
}
int add(int a, int b) {
return a + b;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007 the original author or authors.
* Copyright 2007-2011 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.