読者です 読者をやめる 読者になる 読者になる

XPathを使ってみる

S2JSF htmlunit

 うーむ。難しいですね。とりあえず以下のように感じになりました。add.htmlでformが2つある場合に、何故に「.//form[2]」とやってダメなのかが分からない。。。orz

 public void testAddXpathPage() throws Exception {
   final WebClient webClient = new WebClient();
   final URL url = new URL("http://localhost:8080/s2jsf-example/");
   final HtmlPage hogePage = (HtmlPage)webClient.getPage(url);
   assertEquals( "Home", hogePage.getTitleText() );
   
   XPath xpath = new HtmlUnitXPath(".//a[text()='Add']");
   final HtmlAnchor anchor = (HtmlAnchor)xpath.selectSingleNode(hogePage);
   
   final HtmlPage addPage = (HtmlPage)anchor.click();   
   assertEquals( "Add", addPage.getTitleText() );
   
   String pageText = addPage.asText();
   assertTrue(pageText.contains("足し算"));
   
   xpath = new HtmlUnitXPath(".//form[@id='add']");
   final HtmlForm form = (HtmlForm)xpath.selectSingleNode(addPage);
   
   xpath = new HtmlUnitXPath(".//input[1]");
   final HtmlTextInput textFieldArg1
    = (HtmlTextInput)xpath.selectSingleNode(form);

   textFieldArg1.setValueAttribute("1");

   xpath = new HtmlUnitXPath(".//input[2]");
   final HtmlTextInput textFieldArg2 
    = (HtmlTextInput)xpath.selectSingleNode(form);

   textFieldArg2.setValueAttribute("2");

   xpath = new HtmlUnitXPath(".//input[@type='submit']");
   final HtmlSubmitInput button 
    = (HtmlSubmitInput)xpath.selectSingleNode(form);
   
   final HtmlPage addResultPage = (HtmlPage)button.click();
   
   String page2Text = addResultPage.asText();

   assertTrue(page2Text.contains("1 + 2 = 3"));   
   
 }