Search code examples
groovyaemspockslingsightly

How to create instance of WCMUsePojo in my Prosper spec?


I have a functioning WCMUsePojo Groovy class which is called from a sightly html component. I am trying to create an instance of my WCMUsePojo class for testing based on the content from the Prosper setup method.

It's basically the same type of question as How can I create an instance of WCMUsePojo in a servlet for a specific page? But I don't see it answered and this is specifically about how to unit test methods in WCMUsePojo classes within the Prosper framework. Is there a Java or Groovy equivalent to Sightly's data-sly-use attribute?

def setupSpec() {
    pageBuilder.content {
        page_with_new_gridwrapper {
            'jcr:content'{
                'gridpar' {
                    'my_gridwrapper'('sling:resourceType':'my/components/my_gridwrapper') {

                    }
                }
            }
        }
    }
}

def "Test Page with New Grid Container"(){
    Page page = pageManager.getPage("/content/page_with_new_gridwrapper")

 // the following 2 lines return null :-( 
 // but I would prefer these to return an object with the type MyGridContainerHelper
    MyGridContainerHelper cmp = page.getContentResource().getChild("gridpar/my_gridwrapper").adaptTo(MyGridContainerHelper.class)
    Component cmp2 = WCMUtils.getComponent(page.getContentResource().getChild("gridpar/my_gridwrapper"))

    expect:
    page != null //passes
    page.getContentResource().getChild("gridpar/my_gridwrapper") != null //passes
    cmp != null // fails
    cmp2 != null // fails
    cmp.resourceType == "my/components/my_gridwrapper" // fails

}

Solution

  • I ended up instantiating the object and calling the init method passing in a SimpleBindings object containing the resource I was testing with. This seems to work well for my purposes.

    MyGridContainerHelper gridContainer = new MyGridContainerHelper();
    SimpleBindings bindings = new SimpleBindings()
    bindings.put("resource", page.getContentResource().getChild("gridpar/my_gridwrapper"))
    gridContainer.init(bindings)