2016-11-25 67 views

回答

2

您应该使用css定期查找标题标记并使用getText()来获取标题。

CSS的应该是:“头题”

您的解决方案几乎是好的,你需要注意的可能是个例外,尤其是致命的,如果遇到可以阻止您的套房。

例如find()方法会返回一个对象或null,如果返回null和你在予以使用getText()它会导致致命异常和您的套房将停止。

略有改善方法:

/** 
* @Given /^the page title should be "([^"]*)"$/ 
*/ 
public function thePageTitleShouldBe($expectedTitle) 
{ 
    $titleElement = $this->getSession()->getPage()->find('css', 'head title'); 
    if ($titleElement === null) { 
     throw new Exception('Page title element was not found!'); 
    } else { 
     $title = $titleElement->getText(); 
     if ($expectedTitle !== $title) { 
      throw new Exception("Incorrect title! Expected:$expectedTitle | Actual:$title "); 
     } 
    } 
} 

改进:

  • 处理可能致命异常
  • 抛出异常,如果没有找到元素
  • 抛出异常与细节,如果标题不匹配

请注意,您也可以使用其他方法来检查标题,如:striposstrpos或简单地比较字符串,就像我一样。我更喜欢简单的比较,如果我需要确切的文本或strpos/stripos方法的个人,避免定期异常和像preg_match相关的方法,通常会慢一点。

你可以做的一个主要改进是有一个等待元素并为你处理异常的方法,并用它来代替简单的查找,当你需要根据元素的存在性来决定时,可以使用它像︰如果存在的元素做这个别的..

0

谢谢劳达。是的,这确实有效。写下以下功能:

/** 
    * @Given /^the page title should be "([^"]*)"$/ 
    */ 
    public function thePageTitleShouldBe($arg1) 
    { 
     $actTitle = $this->getSession()->getPage()->find('css','head title')->getText(); 
     if (!preg_match($arg1, $actTitle)) { 
      throw new Exception ('Incorrect title'); 
     } 
    } 
相关问题