Java Reference
In-Depth Information
19.5.2
JUnit-addons
Junit-addons'
PrivateAccessor
class provides methods similar to the ones we imple-
mented from scratch in the previous section. The only differences are the name (
get-
Field()
and
setField()
, instead of
get()
and
set()
); how they're implemented
(although the logic is the same, they use
for
instead of
while
); and the fact that
get-
Field()
doesn't return a parameterized value (because
JU
nit-addons predates Java 5).
Using
PrivateAccessor
directly, we'd rewrite our set
DAO
statement at
setFix-
tures()
as
PrivateAccessor.setField(facade, "userDao", dao);
Although using
PrivateAccessor
directly is fine, it has three drawbacks:
getField()
isn't parameterized (so you'd need to cast its returned value on each test case), the
caller would have to check for
NoSuchFieldException
, and you'd have to add a direct
dependency on a third-party tool on all test cases (which would make it harder to
switch to another tool later on). A better approach would be to use
PrivateAccessor
indirectly in the
TestingHelper
methods, rather than in the test cases themselves, as
shown in listing 19.9.
Listing 19.9
TestingHelper
refactored to use JUnit-addons
[...]
import
junitx.util.PrivateAccessor;
public class
TestingHelperJUnitAddons {
public static void
set( Object object, String fieldName,
Object newValue ) {
try
{
PrivateAccessor.setField(object, fieldName, newValue);
}
catch
(Exception e) {
throw new
RuntimeException( "Could not set value of field '" +
fieldName + "' on object " + object + " to " + newValue, e );
}
}
public static
<T> T get(Object object, String fieldName) {
try
{
Object value = PrivateAccessor.getField(object, fieldName);
@SuppressWarnings("unchecked")
T castValue = (T) value;
return
castValue;
}
catch
(NoSuchFieldException e) {
throw new
RuntimeException( "Could not get value of field '" +
fieldName + "' from object " + object, e );
}
}
PrivateAccessor
also provides a few more methods, such as
invoke()
(to invoke any
instance or static method), and overloaded versions of
getField()
and
setField()
to
deal with static methods.