View Javadoc

    1   package net.sourceforge.pmd.lang.xml.rule;
    2
    3   import static org.junit.Assert.assertEquals;
    4
    5   import java.io.StringReader;
    6   import java.util.ArrayList;
    7   import java.util.List;
    8
    9   import net.sourceforge.pmd.RuleContext;
    10  import net.sourceforge.pmd.lang.Language;
    11  import net.sourceforge.pmd.lang.Parser;
    12  import net.sourceforge.pmd.lang.ast.Node;
    13  import net.sourceforge.pmd.lang.xml.XmlParserOptions;
    14  import net.sourceforge.pmd.lang.xml.ast.XmlNode;
    15  import net.sourceforge.pmd.lang.xml.rule.AbstractXmlRule;
    16
    17  import org.junit.Test;
    18
    19  public class AbstractXmlRuleTest {
    20
    21      @Test
    22      public void testVisit() throws Exception {
    23  	String source = "<?xml version=\"1.0\"?><foo abc=\"abc\"><bar/></foo>";
    24  	XmlParserOptions parserOptions = new XmlParserOptions();
    25  	Parser parser = Language.XML.getDefaultVersion().getLanguageVersionHandler().getParser(parserOptions);
    26  	XmlNode xmlNode = (XmlNode) parser.parse(null, new StringReader(source));
    27  	List<XmlNode> nodes = new ArrayList<XmlNode>();
    28  	nodes.add(xmlNode);
    29
    30  	MyRule rule = new MyRule();
    31  	rule.apply(nodes, null);
    32
    33  	assertEquals(3, rule.visitedNodes.size());
    34  	assertEquals("document", rule.visitedNodes.get(0).toString());
    35  	assertEquals("foo", rule.visitedNodes.get(1).toString());
    36  	assertEquals("bar", rule.visitedNodes.get(2).toString());
    37      }
    38
    39      private static class MyRule extends AbstractXmlRule {
    40  	final List<XmlNode> visitedNodes = new ArrayList<XmlNode>();
    41
    42  	public MyRule() {
    43  	}
    44
    45  	@Override
    46  	public void apply(List<? extends Node> nodes, RuleContext ctx) {
    47  	    visitedNodes.clear();
    48  	    super.apply(nodes, ctx);
    49  	}
    50
    51  	@Override
    52  	protected void visit(XmlNode node, RuleContext ctx) {
    53  	    visitedNodes.add(node);
    54  	    super.visit(node, ctx);
    55  	}
    56      }
    57
    58      public static junit.framework.Test suite() {
    59  	return new junit.framework.JUnit4TestAdapter(AbstractXmlRuleTest.class);
    60      }
    61  }