How to create instance of WCMUsePojo in my Prosper

2019-09-11 01:36发布

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

}

2条回答
2楼-- · 2019-09-11 01:58

To adapt an instance of MyGridContainerHelper from a resource object, you can implement your helper class using Sling Models rather than extending WCMUsePojo. Prosper supports registration of @org.apache.sling.models.annotations.Model-annotated classes by using the following syntax in the setupSpec block of your specification:

slingContext.addModelsForPackage("helper.class.package.name")

This eliminates the need to manually construct a Bindings object and initialize the POJO; the Sling model factory does all the work for you. Since Sightly's "use" attribute supports any class that is adaptable from a Resource or SlingHttpServletRequest, no additional changes are required for your existing Sightly template.

查看更多
叼着烟拽天下
3楼-- · 2019-09-11 02:02

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)
查看更多
登录 后发表回答