我一直在为Web应用程序编写Selenium测试,并且在内部服务器错误的情况下应用程序中似乎存在多个内部服务器错误实例,应用程序显示自定义错误页面并且向用户显示错误ID以追求技术问题团队,以防用户遇到它。
这使得在Selenium执行期间调试测试失败变得有点费力。 我正在考虑使用一些机制来保持轮询页面,在测试中执行每个步骤,以查找是否存在任何内部服务器错误的实例,这是当我遇到Junit规则并想到为它编写自定义注释时,像 -
public class SelTestCase {
protected WebDriver driver;
@Before
public void startDriver() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com/");
}
@After
public void closeDriver() {
driver.quit();
}
}
public class GoogleSearchTest extends SelTestCase {
@Rule
PageChecker pageChecker = new PageChecker();
@Test
@CheckPage
public void testGoogleSearch() {
GoogleHomePage googleHomePage = PageFactory.initElements(driver,
GoogleHomePage.class);
googleHomePage.searchGoogle("Selenium HQ");
assert driver.getPageSource().contains("seleniumhq") : "Selenium headquarter search failed";
}
}
SelTestCase
类创建WebDriver实例来执行测试,这里是PageChecker
类 -
public class PageChecker extends SelTestCase {
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CheckPage {
// page check should take place here (Though not sure if it is right place)
// like if(driver.getPageSource.contains("Internal Server Error") {throw Exception ("Err")}
}
}
这就是我所困扰的,如何继续使用CheckPage发声?
答案 0 :(得分:1)
恕我直言,您的问题有两种解决方案。如果只有一小部分测试需要该功能,那么我就不会使用规则。而是在每个测试中添加一行errorChecker.checkPage(driver)
,并在此方法中实施检查。
如果几乎所有测试都需要它:
通过扩展ExternalResource来将SelTestCase转换为规则。
public class WebDriverRule extends ExternalResource {
public WebDriver driver;
@Override
protected void before() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.com/");
}
@Override
protected void after() {
driver.quit();
}
}
通过扩展Verifier将页面检查代码添加到规则中。
public class PageChecker extends Verifier {
private WebDriverRule webDriverRule;
private enabled = true;
public PageChecker(WebDriverRule webDriverRule) {
this.webDriverRule = webDriverRule;
}
public void disable() {
this.enabled = false;
}
@Override
public void verify() {
if(enabled && notValid())
throw new AssertionError("foo");
}
private boolean notValid() {
WebDriver driver = webDriverRule.driver;
//do something with driver
}
}
使用org.junit.rules.RuleChain来控制两条规则的执行顺序。
public class GoogleSearchTest {
private WebDriverRule webDriverRule = new WebDriverRule();
private PageChecker pageChecker = new PageChecker(webDriverRule);
@Rule
public RuleChain driverAroundPageChecker
= RuleChain.outerRule(webDriverRule).around(pageChecker);
@Test
public void testGoogleSearch() {
GoogleHomePage googleHomePage = PageFactory.initElements(driver,
GoogleHomePage.class);
googleHomePage.searchGoogle("Selenium HQ");
assert driver.getPageSource().contains("seleniumhq") : "Selenium headquarter search failed";
}
@Test
public void testWithouPageCheck() {
pageChecker.disable();
//here is your real test
}
}