Tuesday, March 3, 2009

JSF and Error pages

Have been looking around for a general strategy that for adding an error page to an ADF Application. found there options

Option 1 : make html error pages for each type of exception
Option 2 : make one error page and generalized bean
Option 3 : Make one error page, One task flow for it , In all the managaed beans inside try catch do add return "error_page_task_flow"

Different approaches may be useful in different scenarious

Sunday, March 1, 2009

why we cant mock static methods

This wasn't obvious to me at first, it took me a while to get why we can't mock static methods. So here it goes the reason in one line,

"Static methods aren't polymorphic, they are resolved at compile time, therefor it's not possible to use mock objects to test."

Hope this help you guys who are scratching your head like I was.... (if you are not sure about polymorphism, think of it as late binding)

In my previous posts i showed one of the ways you can mock static methods, but the limitation is that you need to know the implementation of the class. What if i am using another classes static method whose cource code i dont know.

for example : FacesContext fc = facesContext.getInstance();

Mocking singletons and Factories

Mocking singletons ., factories may not be that obvious.

public class Singleton {
private Singleton instance = new Singleton ();
public static Singleton getInstance() {
return instance;
}
}

@Test
public void testSingleton() {
Field instanceField = Singleton .class.getField("instance");
instanceField.setAccessible(true);
Singleton realSingleton = instanceField.get(null);
Singleton mockSingleton = EasyMock.createMock(Singleton .class);
try {
instanceField.set(null, mockSingleton);
// now do your testing, Singleton.getInstance() should now return the mock
} finally {
instanceField.set(null, reallSingleton);
instanceField.setAccessible(false);
}
}

This is fairly hacky, not robust to changes in the singleton class, won't work with a security manager, and it may not work well in the case where the field is instantiated in a static initializer and other fields use that instance when they are initialized. But it probably will work in many cases.