If you wanted to unit test this I'm confident you could do it using JMockit [1] without changing the code. JMockit allows you to mock just about anything (static methods, final methods, constructor invocations). The unit test might look something like:
@Test
public void checkIndexRenders()
{
final List expectedforums= new ArrayList(asList(TEST_FORUM));
new NonStrictExpections()
{
@Mocked Forum forum;
@Mocked Topic topic;
@Mocked Post post;
{
Forum.findAll(); result = expectedforums;
Topic.count(); result = 5;
Post.count(); result = 10;
}
};
Forums.index()
// your assertions ...
}
I come from a DI background, but the JMockit framework has changed my view of what untestable code is.
Apologies for the tangent, but is this considered idiomatic Java these days? As a person who knows/knew Java pretty well but has been out of the game for a few years, this code seems highly surprising. Instantiating an anonymous subclass with a static initializer to... I suppose be able to use those @Mocked annotations. Then assigning result in that anonymous initializer block, which I must assume works through black magic.
No criticism of your code example. I think figuring out how to make Java do this is very impressive. I just wonder if it's considered wise to do this sort of thing in production code?
(Edited to correct that I don't think that's a static initializer block.)
Generally this would not be done in production code. jMockit is pretty out there, syntax - wise, and the anonymous inner classes are generally discouraged in production code. In tests are generally fine though. which is why jMockit can get away with it.
[1] http://code.google.com/p/jmockit/