使用Selenium,是否可以创建模拟WebElement以便在单元测试中使用? [英] Using Selenium, is it possible to create a mock WebElement to use in a unit test?
问题描述
使用Selenium,是否可以创建用于单元测试的虚拟WebElement?
Using Selenium, is it possible to create a virtual WebElement to use in a unit test?
@Test
public void testIt() {
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement we = (WebElement)js.executeScript("code to create and return a input element");
assertTrue("default value", we.getText());
}
我曾考虑过使用Spy或Mock对象,但是WebElement没有任何"setter"方法,因此一旦创建WebElement实例,我就不知道如何给它赋值.
I thought about using a Spy or Mock object, but WebElement doesn't have any "setter" methods and so once I create a WebElement instance, I don't know how I would give it values.
例如,是否可以将HtmlUnit Web元素转换为Selenium WebElement(包含属性)?
For example, would it be possible to convert a HtmlUnit web element to a Selenium WebElement (that contains attributes)?
final String html = "<html><head></head><body id='tag'><b>text</b></body></html>";
final HtmlPage page = loadPage(html);
final HtmlUnitWebElement node = page.getHtmlElementById("tag");
WebElement we = node.findElement(By.xpath(".//b"));
推荐答案
您可以编写具有自己实现的代理类.我不了解Java Selenium,但是.Net Selenium具有PageObjectFactory使用的代理WebDriver,并且此代理WebDriver返回以惰性方式工作的代理WebElement类-它在对该对象的首次访问时进行初始化.
You can write a proxy class with own implementation. I dont know about Java Selenium, but .Net Selenium has proxy WebDriver that used by PageObjectFactory and this proxy WebDriver returns proxy WebElement class that works in lazy way - it does initialization on the first access to that object.
This may help you as example - https://github.com/SeleniumHQ/selenium/tree/master/java/client/src/org/openqa/selenium/support/events . You can check EventFiringWebDriver
that works like a proxy too and creates proxy EventFiringWebElement
object.
因此,您可以为将具有设置器的WebElement编写自己的实现,并将其与测试数据一起使用.
So you can write own implementation for WebElement that will have setters and you can use them with test data.
这篇关于使用Selenium,是否可以创建模拟WebElement以便在单元测试中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!