How to create instance of WCMUsePojo in my Prosper spec?

孤人 提交于 2019-12-12 01:57:37

问题


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

}

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/38212997/how-to-create-instance-of-wcmusepojo-in-my-prosper-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!