Search code examples
junit4tapestry

Tapestry: How to test using JUnit4 when there is @InjectComponent


I am testing using Junit4 with eclipse. I want to test the function expandAll

public void expandAll(TreeExpansionModel<TreeData> expansionModel)
 {  
    List<TreeNode<TreeData>> roots = getTreeModel().getRootNodes();
    for (TreeNode<TreeData> root : roots) 
    {
        expandAllNode(root, expansionModel);
    }
 }

 private void expandAllNode(TreeNode<TreeData> node, TreeExpansionModel<TreeData> expansionModel) 
{ 
       if (node.getHasChildren()) 
      { 
          expansionModel.markExpanded(node); 
          for (TreeNode child : node.getChildren()) 
         { 
             expandAllNode(child, expansionModel); // this is a recursive call 
          } 
       } 
} 

The problem I am having is the expansionModel. In my program(not test), I pass in the expansionModel using tree. Here is the code fragment from java.

@InjectComponent
private Tree tree;

public void onExpandAll()
 {
     expansionModel = tree.getExpansionModel();
     treeFunction.expandAll(expansionModel);

     ajaxResponseRenderer.addRender(treeZone);

 }

I have tried in my test using

tree = new Tree();
expansionModel = tree.getExpansionModel();
testing.expandAll(expansionModel);

but the expansionModel I get is null. How do I go about testing with @InjectComponent tree? Any help would be appreciated. Thanks.


Solution

  • Unit testing of pages that contain components can be difficult, it often requires adding special constructors to your components that are ONLY required for testing. This becomes even harder when the components are from an external source (ie tapestry-core).

    Have you considered selenium testing instead? I often find that unit testing pages requires lots of effort for little gain.

    If you really want to unit test this page, I suggest that you refactor the code to isolate the Tree dependency:

    @InjectComponent
    private Tree tree;
    
    public void onExpandAll() {
        onExpandAll(tree.getExpansionModel());
    }
    
    protected void onExpandAll(TreeExpansionModel expansionModel) {
        treeFunction.expandAll(expansionModel);
        ajaxResponseRenderer.addRender(treeZone);
    }
    

    Then you can unit test the second onExpandAll method without needing a Tree instance using DefaultTreeExpansionModel or similar.