Selenide UI 自动化测试

时间:2024-08-04 16:34:14

    我没有拼写错误,确实不是 Selenium ,但是,只要是 Web UI 自动化测试框架,基本上都是基于Selenium 的。Selenide 也不例外。那为啥不直接用Selenium呢? 因为原生的 Selenium 不好用啊!

举个例子,用原生成Selenium去写 显式等待。

   ……

   //显式等待, 针对某个元素等待
WebDriverWait wait = new WebDriverWait(driver,10,1); wait.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver text) {
return text.findElement(By.id("kw"));
}
}).sendKeys("selenium");

  如果每一个元素都设置显示等待(为了保证脚本的稳定性),你不会疯掉? 所以, 用 Selenium 做UI 自动化测试,不去封装 Selenium, 不去考虑设计模式。你的项目很难做得好!

什么是 Selenide ?

Concise UI Tests with Java!  所以,其它语言的同学靠边。

Selenide = UI Testing Framework powered by Selenium WebDriver

如何学习?

Github 项目地址:https://github.com/codeborne/selenide

官方网站:http://selenide.org/index.html

如何安装?

这里只介绍 Maven 安装:

        <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.11</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>com.codeborne</groupId>
<artifactId>selenide</artifactId>
<version>4.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
<scope>provided</scope>
</dependency> <dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
<scope>provided</scope>
</dependency>

我的测试用例是基于 testNG 单元测试框架运行的,所以,把 TestNG 的配置加进来了。

Selenide 在安装运行的过程中报错: Failed to load class "org.slf4j.impl.StaticLoggerBinder"    所以,指定了一下slf4j 和 log4j 的版本。

如何使用?

Selenium 老司机直接看代码,不管怎么的封装, 一眼就能看出来它的“特色”。 官方 demo。

@Test
public void userCanLoginByUsername() {
open("/login");
$(By.name("user.name")).setValue("johny");
$("#submit").click();
$(".loading_progress").should(disappear); // Waits until element disappears
$("#username").shouldHave(text("Hello, Johny!")); // Waits until element gets text
}

URL 地址在哪儿? 浏览器怎改? 估计你跑不起来! 反正,我没跑起来。 打开 Friefox 浏览器就不动了。

好在!作者很负责,在官方上放了一段自己录制的10分钟教程(其实,我听不懂英文,但看他的操作就明白了。哈哈!)

import com.codeborne.selenide.Configuration;
import org.testng.annotations.Test; import static com.codeborne.selenide.CollectionCondition.size;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*; public class SelenideTest { @Test
public void TestBaidu() throws InterruptedException {
Configuration.browser = "Chrome";
Configuration.baseUrl="https://www.baidu.com";
open("/");
$("#kw").setValue("selenide");
$("#su").click();
Thread.sleep(3000);
// 断言
$$("h3 > a").shouldHave(size(9));
$("h3 > a").setValue(String.valueOf(text("selenide_百度翻译")));
} }

这才是可以运行的第一个demo。

通过这第一个demo,感官性的谈谈它的优点:

1、 API更简洁

2、默认使用 CSS 定位

3、自己封装了断言

4、错误后自动截图 (不信你运行上面的代码试试)

5、自动关闭浏览器。

缺点:

不知道为什么 我的 Chrome 浏览器启动的特别慢。

希望我进一步介绍 Selenide UI自动化框架的使用,欢迎留言!

--------------

我自己也有封装 selenium  的框架:

java selenium :https://github.com/defnngj/knife

python selenium : https://github.com/defnngj/pyse