Update:
Some 10 years later perhaps the best way to test a private method, or any inaccessible member, is via @Jailbreak
from the Manifold framework.
@Jailbreak Foo foo = new Foo();
// Direct, *type-safe* access to *all* foo's members
foo.privateMethod(x, y, z);
foo.privateField = value;
This way your code remains type-safe and readable. No design compromises, no overexposing methods and fields for the sake of tests.
If you have somewhat of a legacy Java application, and you're not allowed to change the visibility of your methods, the best way to test private methods is to use reflection.
Internally we're using helpers to get/set private
and private static
variables as well as invoke private
and private static
methods. The following patterns will let you do pretty much anything related to the private methods and fields. Of course, you can't change private static final
variables through reflection.
Method method = TargetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
And for fields:
Field field = TargetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
Notes:
1. TargetClass.getDeclaredMethod(methodName, argClasses)
lets you look into private
methods. The same thing applies for
getDeclaredField
.
2. The setAccessible(true)
is required to play around with privates.
You can use either date or strftime. In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)
For example:
<?php echo date("Y"); ?>
On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the php manual on date:
To format dates in other languages,
you should use the setlocale() and
strftime() functions instead of
date().
From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.
Best Answer
I'm using Zend_Test to completely test all controllers. It's quite simple to set up, as you only have to set up your bootstrap file (the bootstrap file itself should NOT dispatch the front controller!). My base test-case class looks like this:
where
Application::setup();
does all the setup up tasks which also set up the real application. A simple test then would look like this:That's all...