使用Selenium和HTML中的动态ID进行Java测试
Selenium最酷的方面之一是,您不仅可以使用网站进行录制,还可以将其实际用作junit测试。
首先,我将在Firefox中安装Selenium(因为这是正式版本)并进行快速测试。 重要的是要注意,Selenium将为您提供多种不同的方式来记住您调用了哪个html标记。 例如,它可以仅调用页面上的特定ID。
但是,当使用Liferay下的诸如JSF之类的门户系统时,id值是即时生成的,因此您需要记录一次测试,然后再也无法成功运行它。
Selenium的一个非常不错的功能是您可以调用HTML xpath,因此在Liferay示例中,您的代码仍会找到需要单击的标记。 可以说我记录自己登录下面的页面…
现在,由于此页面是使用liferay生成的,因此我可以看到表单的输入文本ID为…
<input aria-required="true" class="aui-field-input aui-field-input-text aui-form-validator-error" id="_58_login" name="_58_login" type="text" value="" />
由于Liferay下的JSF会非常定期地为该文本框创建一个新的ID(我相信每次重启服务器,尽管可能会更频繁),这意味着我们不能仅仅获取ID并加入其中,因为测试将只运行一次。
但是,我们可以做的是通过直接使用html标签直接连接到liferay中,因为每次Liferay加载JSF时它都不会不同。 我注意到我必须对Liferay中的每个页面使用相同的技术,因为每次访问该页面时,几乎所有通过JSF呈现的html的id都有一个不同的id。
然后我们可以从文件菜单File | File中将其导出到junit类。 将测试用例导出为…| Java / JUnit 4 / Web驱动程序,它将为我们提供以下用于运行和测试的类。
import static org.junit.Assert.fail; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class TestExample { private WebDriver driver; private String baseUrl; private StringBuffer verificationErrors = new StringBuffer(); @Before public void setUp() throws Exception { driver = new FirefoxDriver(); baseUrl = "http://localhost:8080"; driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testExample() throws Exception { driver.get(baseUrl + "/en_GB/web/myapp/home?p_p_id=58&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&saveLastPath=0&_58_struts_action=%2Flogin%2Flogin"); driver.findElement(By.xpath("//span/input")).clear(); driver.findElement(By.xpath("//span/input")).sendKeys("user"); driver.findElement(By.xpath("//span[2]/span/span/input")).clear(); driver.findElement(By.xpath("//span[2]/span/span/input")).sendKeys("pass"); driver.findElement(By.xpath("//div/span/span/input")).click(); } @After public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } }
翻译自: https://www.javacodegeeks.com/2013/06/java-testing-with-selenium-and-dynamic-ids-in-html.html