使用Selenium,是否可以创建模拟WebElement以便在单元测试中使用? [英] Using Selenium, is it possible to create a mock WebElement to use in a unit test?

查看:94
本文介绍了使用Selenium,是否可以创建模拟WebElement以便在单元测试中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆