mkoryak mkoryak - 1 year ago 123
Groovy Question

Mocking FacesContext

I am trying to add some unit tests to a JSF application. This application didnt rely heavily on any best practices, so many service methods use the

to pull data from managed session beans like so:

(this is inside a util class)

public static Object getPageBean(String beanReference) {
FacesContext fc = FacesContext.getCurrentInstance();
VariableResolver vr = fc.getApplication().getVariableResolver();
return vr.resolveVariable(fc, beanReference);

What would be the best way to mock this? I am using groovy so i have a few more options for creating classes that i cant normally create.

Answer Source

in my case i was able to mock it in pure groovy. i provide a map of MockBeans that it can return:

private FacesContext getMockFacesContext(def map){
        def fc = [
          "getApplication": {
            return ["getVariableResolver": {
              return ["resolveVariable": { FacesContext fc, String name ->
                return map[name]
              }] as VariableResolver
            }] as Application
          "addMessage": {String key, FacesMessage val ->
            println "added key: [${key}] value: [${val.getDetail()}] to JsfContext messages"
          "getMessages": {return null}
        ] as FacesContext;
        return fc;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download