MyWork
;first make sure the number of arguments passed into the scripts is more than 1 If $CmdLine[0]<2 Then Exit EndIf ;if parmas num <2 ,then break ;$CmdLine[0] ;参数的数量 ;$CmdLine[1] ;第一个参数 (脚本名称后面) ;$CmdLine[2] ;第二个参数 ;都是从cmd传入参数 handleUpload($CmdLine[1],$CmdLine[2]) ;定义上传函数,有两个参数,第一个是浏览器名字,第二参数是文件路径 Func handleUpload($browser, $uploadfile) Dim $title ;定义一个title变量 ;根据弹窗的title来判断是什么浏览器 If $browser="ie" Then ; 代表IE浏览器 $title="选择要加载的文件" ElseIf $browser="chrome" Then ; 代表谷歌浏览器 $title="打开" ElseIf $browser="firefox" Then ; 代表火狐浏览器 $title="文件上传" EndIf if WinWait($title,"",4) Then ;等待弹出出现,最大等待时间是4秒 WinActivate($title) ;找到弹出窗口之后,激活当前窗口 ControlSetText($title,"","Edit1",$uploadfile) ;把文件路径放入输入框,此”Edit1“是用FinderTool获取到的 ControlClick($title,"","Button1") ;点击保存或者打开或者上传按钮,此“Button1”使用FinderTool获取到的 Else Return False EndIf EndFunc
<?xml version="1.0" encoding="UTF-8"?>
<Pages>
<Page keyword="登录页面">
<UIElement keyword="用户代码输入框" by="cssSelector" value="[placeholder='请输入用户名']"></UIElement>
<UIElement keyword="密码输入框" by="cssSelector" value="[placeholder='请输入密码']"></UIElement>
<UIElement keyword="登录按钮" by="xpath" value="//span[contains(text(),'登录')]/parent::button"></UIElement>
</Page>
</Pages>
package com.cpic.caf.utils; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.Calendar; import java.util.Date; public class DateUtil { /** * 得到当前一天的下一天 * @return */ public static String getTomorrow() { Calendar nowTime = Calendar.getInstance(); Date nowDate = (Date) nowTime.getTime(); //得到当前时间 Calendar afterTime = Calendar.getInstance(); afterTime.add(Calendar.DAY_OF_MONTH, 1); //当前月份+5 // afterTime.add(Calendar.MINUTE, 5); //当前分钟+5 Date afterDate = (Date) afterTime.getTime(); System.out.println( new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(afterDate)); return new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(afterDate); } /** * 得到当前一天的下一天的第二年 * @return */ public static String getTomorrowYear() { Calendar nowTime = Calendar.getInstance(); Date nowDate = (Date) nowTime.getTime(); //得到当前时间 Calendar afterTime = Calendar.getInstance(); // afterTime.add(Calendar.MINUTE, 5); //当前分钟+5 afterTime.add(Calendar.DAY_OF_MONTH, 1); //当前月份+5 afterTime.add(Calendar.YEAR, 1); //当前月份+5 Date afterDate = (Date) afterTime.getTime(); System.out.println( new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(afterDate)); return new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(afterDate); } public static void main(String[] args) { System.out.println(getTomorrowYear().split(" ")[0]); getTomorrow(); } //判断选择的日期是否是本周 public static boolean isThisWeek(String time) { Long convertTimeToLong = convertTimeToLong(time); Calendar calendar = Calendar.getInstance(); int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR); calendar.setTime(new Date(convertTimeToLong)); int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR); if(paramWeek==currentWeek){ return true; } return false; } //判断选择的日期是否是今天 public static boolean isToday(long time) { return isThisTime(time,"yyyy-MM-dd"); } //判断选择的日期是否是本月 public static boolean isThisMonth(long time) { return isThisTime(time,"yyyy-MM"); } private static boolean isThisTime(long time,String pattern) { Date date = new Date(time); SimpleDateFormat sdf = new SimpleDateFormat(pattern); String param = sdf.format(date);//参数时间 String now = sdf.format(new Date());//当前时间 if(param.equals(now)){ return true; } return false; } Long millisecond = Instant.now().toEpochMilli(); // 精确到毫秒 Long second = Instant.now().getEpochSecond();// 精确到秒 /** * 将Long类型的时间戳转换成String 类型的时间格式,时间格式为:yyyy-MM-dd HH:mm:ss */ public static String convertTimeToString(Long time){ // Assert.notNull(time, "time is null"); DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time),ZoneId.systemDefault())); } /** * 将字符串转日期成Long类型的时间戳,格式为:yyyy-MM-dd HH:mm:ss */ public static Long convertTimeToLong(String time) { // Assert.notNull(time, "time is null"); DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime parse = LocalDateTime.parse(time, ftf); return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } /** * 取本月第一天 */ public static LocalDate firstDayOfThisMonth() { LocalDate today = LocalDate.now(); return today.with(TemporalAdjusters.firstDayOfMonth()); } /** * 取本月第N天 */ public static LocalDate dayOfThisMonth(int n) { LocalDate today = LocalDate.now(); return today.withDayOfMonth(n); } /** * 取本月最后一天 */ public static LocalDate lastDayOfThisMonth() { LocalDate today = LocalDate.now(); return today.with(TemporalAdjusters.lastDayOfMonth()); } /** * 取本月第一天的开始时间 */ public static LocalDateTime startOfThisMonth() { return LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN); } /** * 取本月最后一天的结束时间 */ public static LocalDateTime endOfThisMonth() { return LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX); } //总结&说明: // 1、第2条和第3条中的Assert.notNull(time, "time is null"); 是spring框架的util方法,用其他方法判空也是一样,不过我觉得spring的这个写法比较好,大家可以参考他的思路或者说做法。 // 2、建议大家一定要将日期时间相关处理方法集中起来,放到一个DateAndTimeUtils之类的工具类中统一使用和管理。这样做第一避免重复造轮子,第二避免同一量车造出来各式各样的轮子。(想象一下SimpleDateFormat和DateTimeFormatter搅和在一起是什么样的一种酸爽0.0) }
package pojo; import java.util.ArrayList; import java.util.List; public class Page { private String keyword; List<UIElement> uiElementList = new ArrayList<UIElement>(); public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public List<UIElement> getUiElementList() { return uiElementList; } public void setUiElementList(List<UIElement> uiElementList) { this.uiElementList = uiElementList; } public Page(String keyword, List<UIElement> uiElementList) { super(); this.keyword = keyword; this.uiElementList = uiElementList; } public Page() { super(); } @Override public String toString() { return "Page [keyword=" + keyword + ", uiElementList=" + uiElementList + "]"; } }
package pojo; public class UIElement { /** * 元素关键字 */ private String keyword; /** * 元素定位方式 */ private String by; /** * 元素定位值 */ private String value; public String getKeyword() { return keyword; } public void setKeyword(String keyword) { this.keyword = keyword; } public String getBy() { return by; } public void setBy(String by) { this.by = by; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public UIElement(String keyword, String by, String value) { super(); this.keyword = keyword; this.by = by; this.value = value; } public UIElement() { super(); } @Override public String toString() { return "UIElement [keyword=" + keyword + ", by=" + by + ", value=" + value + "]"; } }
log4j.properties
log4j.rootLogger = INFO,console,file
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern = [%p] %d{yyyy-MM-dd HH:mm:ss} method: %l----%m%n
log4j.appender.file = org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File = log/api_auto.log
log4j.appender.file.Append = true
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} method: %l - [ %p ]----%m%n
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single user,
| and is normally provided in ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all Maven
| users on a machine (assuming they're all using the same Maven
| installation). It's normally provided in
| ${maven.conf}/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start at
| getting the most out of your Maven installation. Where appropriate, the default
| values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ${user.home}/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<localRepository>C:\apache-maven-3.6.1\repository</localRepository>
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set to false,
| maven will use a sensible default value, perhaps based on some other setting, for
| the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when executing a build.
| This will have an effect on artifact downloads, artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
| when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to the network.
| Unless otherwise specified (by system property or command-line switch), the first proxy
| specification in this list marked as active will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used within the system.
| Authentication profiles can be used whenever maven must make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a particular server, identified by
| a unique name within the system (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
| used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote repositories.
|
| It works like this: a POM may declare a repository to use in resolving certain artifacts.
| However, this repository may have problems with heavy traffic at times, so people have mirrored
| it to several places.
|
| That repository definition will have a unique id, so we can create a mirror reference for that
| repository, to be used as an alternate download site. The mirror site will be the preferred
| server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways, and which can modify
| the build process. Profiles provided in the settings.xml are intended to provide local machine-
| specific paths and repository locations which allow the build to work in the local environment.
|
| For example, if you have an integration testing plugin - like cactus - that needs to know where
| your Tomcat instance is installed, you can provide a variable here such that the variable is
| dereferenced during the build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
| section of this document (settings.xml) - will be discussed later. Another way essentially
| relies on the detection of a system property, either matching a particular value for the property,
| or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
| value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
| Finally, the list of active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
| repositories, plugin repositories, and free-form properties to be used as configuration
| variables for plugins in the POM.
|
|-->
<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated using one or more of the
| mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
| or the command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a consistent naming convention
| for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
| This will make it more intuitive to understand what the set of introduced profiles is attempting
| to accomplish, particularly when you only have a list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
<!--
| Here is another profile, activated by the system property 'target-env' with a value of 'dev',
| which provides a specific path to the Tomcat instance. To use this, your plugin configuration
| might hypothetically look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
| anything, you could just leave off the <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MyProject</groupId>
<artifactId>CommonSubject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<aspectj.version>1.8.10</aspectj.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>2.12.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<!-- maven-surefire-plugin 配合testng/junit执行测试用例的maven插件 -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<!-- 测试失败后,是否忽略并继续测试 -->
<testFailureIgnore>true</testFailureIgnore>
<suiteXmlFiles>
<!-- testng配置文件名称 -->
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
<!--设置参数命令行 -->
<argLine>
<!-- UTF-8编码 -->
-Dfile.encoding=UTF-8
<!-- 配置拦截器 -->
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
<systemProperties>
<property>
<!-- 配置 allure 结果存储路径 -->
<name>allure.results.directory</name>
<value>${project.build.directory}/allure-results</value>
</property>
</systemProperties>
</configuration>
<dependencies>
<!-- aspectjweaver maven坐标 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<suite name="Suite" parallel="tests" thread-count="2">
<!-- 第一个线程对应的配置 启动本地chrome浏览器 -->
<test name="Test_thread01">
<parameter name="browserName" value="firefox"></parameter>
<classes>
<class name="test" />
</classes>
</test>
<!-- 第二个线程对应的配置 启动本地chrome浏览器 -->
<test name="Test_thread02">
<parameter name="browserName" value="chrome"></parameter>
<classes>
<class name="test" />
</classes>
</test>
<listeners>
<!-- 报表的监听器,监听用例的执行结果,截图 -->
<listener class-name="com.lemon.listener.AllureReportListener"></listener>
<!-- 失败重试机制的监听器 -->
<listener class-name="com.lemon.listener.RetryListener"></listener>
</listeners>
</suite> <!-- Suite -->
package common; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.apache.tika.metadata.WordPerfect; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import pojo.Page; import pojo.UIElement; import utils.BrowserUtils; import utils.XmlUtils; public class BasePage { private final static Logger logger = Logger.getLogger(BasePage.class); /** * 获取浏览器 * @return 浏览器 */ public static WebDriver getBroswer() { return BrowserUtils.getDriver(); } /** * 获取JavascriptExecutor * @return JavascriptExecutor */ public static JavascriptExecutor getJs() { return BrowserUtils.getJavascriptExecutor(); } /** * 获取WebDriverWait * @return WebDriverWait */ public static WebDriverWait getWait() { return BrowserUtils.getWebDriverWait(); } /** * 创建本地浏览器或者远程浏览器 * @param type type→本地/远程 * @param browserType 浏览器类型 */ public static void createBroswer(String type,String browserType) { logger.info("================================打开"+type+"浏览器("+browserType+") ========================================"); if (type.contains("本地")) { BrowserUtils.openBrowser(browserType);; }else if (type.contains("远程")) { BrowserUtils.openRemoteBrowser(browserType); } } /** * 创建本地浏览器 * @param browserType 浏览器类型 */ public static void createBrowser(String browserType) { logger.info("================================打开远程端浏览器("+browserType+") ========================================"); BrowserUtils.openBrowser(browserType); } /** * 创建远程浏览器 * @param browserType 浏览器类型 */ public static void createRemoteBrowser(String browserType) { logger.info("================================打开本地浏览器("+browserType+") ========================================"); BrowserUtils.openRemoteBrowser(browserType); } /** * 清楚缓存 */ public static void ClearCache () { logger.info("================================开始清除缓存 ========================================"); Set<Cookie> coo = getBroswer().manage().getCookies(); //打印Cookie logger.info("cookies信息:【"+coo.toString()+"】"); //清除所有的缓存 getBroswer().manage().deleteAllCookies(); } /** * 跳转到指定的url * @param url 需跳转的url地址 */ public static void getUrl(String url) { logger.info("浏览器跳转到:【"+url+"】"); getBroswer().get(url); } /** * 硬性等待 * @param time 毫秒 */ public static void waitTime(int time) { try { logger.info("线程等待:【"+(double)time/1000+"】秒"); Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 最大化窗口 */ public static void maxWindow() { logger.info("window窗口最大化"); getBroswer().manage().window().maximize(); } /** * 根据获取的标题来切换句柄 获取的标题包含预期的标题才能切换 * @param title 标题 */ public void switchWindowByTitle(String title) { Set<String> handles = getBroswer().getWindowHandles(); logger.info("获取【handles大小】为:【"+handles.size()+"】,【获取的handles】为:【"+handles.toString()+"】"); for (String handle : handles) { if (getBroswer().getTitle().contains(title)) { logger.info("当前句柄的【标题】:【"+getBroswer().getTitle()+"】,符合预期的标题,切换成功"); break; }else { logger.info("当前句柄的【标题】:【"+getBroswer().getTitle()+"】,切换句柄,寻找符合标题的句柄"); getBroswer().switchTo().window(handle); } } } /** * 根据获取的url来切换句柄 获取的标题包含预期的标题才能切换 * @param url 标题 */ public void switchWindowByCurrentUrl(String url) { Set<String> handles = getBroswer().getWindowHandles(); logger.info("获取【handles大小】为:【"+handles.size()+"】,【获取的handles】为:【"+handles.toString()+"】"); for (String handle : handles) { if (getBroswer().getCurrentUrl().contains(url)) { logger.info("当前句柄的【url】:【"+getBroswer().getCurrentUrl()+"】,符合预期的标题,切换成功"); break; }else { logger.info("当前句柄的【url】:【"+getBroswer().getCurrentUrl()+"】,切换句柄,寻找符合标题的句柄"); getBroswer().switchTo().window(handle); } } } /** * 等待单个元素存在在dom对象中,但不一定可见 * @param locator By 对象定位信息 * @return 返回存在dom 单个WebElement中元素,否则抛出异常 */ public static WebElement waitPresenceOfElementLocated(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,等待元素在dom中存在"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.presenceOfElementLocated(locator)).toString()+"】"); return getWait().until(ExpectedConditions.presenceOfElementLocated(locator)); } /** * 等待单个元素存在在dom对象中,但不一定可见 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回存在dom 单个WebElement中元素,否则抛出异常 */ public static WebElement waitPresenceOfElementLocated(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,等待元素在dom中存在"); By by = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【元素定位信息】为:【"+by.toString()+"】"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.presenceOfElementLocated(by)).toString()+""); return getWait().until(ExpectedConditions.presenceOfElementLocated(by)); } /** * 等待多个个元素存在在dom对象中,但不一定可见 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回存在dom 多个WebElement中元素-List<WebElement>,否则抛出异常 */ public static List<WebElement> waitPresenceOfAllElementsLocatedBy(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,等待元素们在dom中存在"); By by = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【元素定位信息】为:【"+by.toString()+"】"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.presenceOfAllElementsLocatedBy(by)).toString()+"】,其个数为【"+getWait().until(ExpectedConditions.presenceOfAllElementsLocatedBy(by)).size()+"】"); return getWait().until(ExpectedConditions.presenceOfAllElementsLocatedBy(by)); } /** * 等待多个个元素存在在dom对象中,但不一定可见 * @param locator By 对象定位信息 * @return 返回存在dom 多个WebElement中元素-List<WebElement>,否则抛出异常 */ public static List<WebElement> waitPresenceOfAllElementsLocatedBy(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,等待元素们在dom中存在"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.presenceOfAllElementsLocatedBy(locator)).toString()+"】,其个数为【"+getWait().until(ExpectedConditions.presenceOfAllElementsLocatedBy(locator)).size()+"】"); return getWait().until(ExpectedConditions.presenceOfAllElementsLocatedBy(locator)); } //=================== /** * 等待单个元素在页面可见 * @param locator By 对象定位信息 * @return 返回页面可见的 单个WebElement中元素,否则抛出异常 */ public static WebElement waitVisibilityOfElementLocated(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,等待元素在页面可见"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.visibilityOfElementLocated(locator)).toString()+"】"); return getWait().until(ExpectedConditions.visibilityOfElementLocated(locator)); } /** * 等待单个元素在页面可见 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回页面可见的 单个WebElement中元素,否则抛出异常 */ public static WebElement waitVisibilityOfElementLocated(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,等待元素在在页面可见"); By by = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【元素定位信息】为:【"+by.toString()+"】"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.visibilityOfElementLocated(by)).toString()+""); return getWait().until(ExpectedConditions.visibilityOfElementLocated(by)); } /** * 等待单个元素在页面可见 * @param element 需要等待的元素 * @return 返回页面可见的 单个WebElement中元素,否则抛出异常 */ public static WebElement waitVisibilityOfElementLocated(WebElement element) { logger.info("获取【元素】为:【"+element.toString()+"】,等待页面可见"); return getWait().until(ExpectedConditions.visibilityOf(element)); } /** * 等待多个个元素在页面可见 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回存在页面 多个WebElement中元素-List<WebElement>,否则抛出异常 */ public static List<WebElement> waitVisibilityOfAllElementsLocatedBy(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,等待元们素在页面可见"); By by = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【元素定位信息】为:【"+by.toString()+"】"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)).toString()+"】,其个数为【"+getWait().until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)).size()+"】"); return getWait().until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); } /** * 等待多个个元素在页面可见 * @param locator By 对象定位信息 * @return 返回存在页面 多个WebElement中元素-List<WebElement>,否则抛出异常 */ public static List<WebElement> waitVisibilityOfAllElementsLocatedBy(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,等待元素们在页面可见"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator)).toString()+"】,其个数为【"+getWait().until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator)).size()+"】"); return getWait().until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator)); } /** * 等待多个个元素在页面可见 * @param locator By 对象定位信息 * @return 返回存在页面 多个WebElement中元素-List<WebElement>,否则抛出异常 */ public static List<WebElement> waitVisibilityOfAllElementsLocatedBy(WebElement ... elements) { logger.info("获取【locator定位信息】为:【"+elements.toString()+"】,等待元素们在页面可见"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.visibilityOfAllElements(elements)).toString()+"】,其个数为【"+getWait().until(ExpectedConditions.visibilityOfAllElements(elements)).size()+"】"); return getWait().until(ExpectedConditions.visibilityOfAllElements(elements)); } /** * 等待单个元素可被点击 * @param locator By 对象定位信息 * @return 返回页面可点击单个WebElement中元素,否则抛出异常 */ public static WebElement waitElementToBeClickable(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,等待元素可被点击"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.elementToBeClickable(locator)).toString()+"】"); return getWait().until(ExpectedConditions.elementToBeClickable(locator)); } /** * 等待单个元素可被点击 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回页面可点击单个WebElement中元素,否则抛出异常 */ public static WebElement waitElementToBeClickable(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,等待元素可被点击"); By by = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【元素定位信息】为:【"+by.toString()+"】"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.elementToBeClickable(by)).toString()+""); return getWait().until(ExpectedConditions.elementToBeClickable(by)); } /** * 等待单个元素可被点击 * @param element 需要等待的元素 * @return 返回页面可点击单个WebElement中元素,否则抛出异常 */ public static WebElement waitElementToBeClickable(WebElement element) { logger.info("获取【元素】为:【"+element.toString()+"】,等待元素可被点击"); return getWait().until(ExpectedConditions.elementToBeClickable(element)); } /** * 等待Frame可以跳转并跳转进去 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回webDriver实例 */ public static WebDriver waitFrameToBeAvailableAndSwitchToIt(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,等待Frame可以跳转并跳转进去"); By by = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【元素定位信息】为:【"+by.toString()+"】"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(by)).toString()+""); return getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(by)); } /** * 等待Frame可以跳转并跳转进去 * @param element 需要等待的元素 * @return 返回webDriver实例 */ public static WebDriver waitFrameToBeAvailableAndSwitchToIt(WebElement element) { logger.info("获取【元素】为:【"+element.toString()+"】,等待Frame可以跳转并跳转进去"); return getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(element)); } /** * 等待Frame可以跳转并跳转进去 * @param frameLocator (id or name) * @return 返回webDriver实例 */ public static WebDriver waitFrameToBeAvailableAndSwitchToIt(String frameLocator) { logger.info("获取【frame (id or name)】为:【"+frameLocator+"】,等待Frame可以跳转并跳转进去"); return getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameLocator)); } /** * 等待Frame可以跳转并跳转进去 * @param frameLocator index * @return 返回webDriver实例 */ public static WebDriver waitFrameToBeAvailableAndSwitchToIt(int frameLocator) { logger.info("获取【frame (index)】为:【"+frameLocator+"】,等待Frame可以跳转并跳转进去"); return getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(frameLocator)); } /** * 等待Frame可以跳转并跳转进去 * @param locator By 对象定位信息 * @return 返回webDriver实例 */ public static WebDriver waitFrameToBeAvailableAndSwitchToIt(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,等待Frame可以跳转并跳转进去"); logger.info("返回的元素有【"+ getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(locator)).toString()+"】"); return getWait().until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(locator)); } /** * 点击某个元素 * @param locator By定位对象 */ public static void click(By locator ) { try { logger.info("点击了等待可以点击的元素,其定位信息【"+locator.toString()+"】"); waitElementToBeClickable(locator).click(); } catch (Exception e) { try { logger.info("点击了等待可以点击的元素失败,通过js点击,其定位信息【"+locator.toString()+"】"); clickByJs(waitPresenceOfElementLocated(locator)); } catch (Exception e2) { e.printStackTrace(); } } } /** * 点击某个元素 * @param element 元素对象 */ public static void click(WebElement element ) { try { logger.info("点击了等待可以点击的元素,其元素信息【"+element.toString()+"】"); waitElementToBeClickable(element).click(); } catch (Exception e) { try { logger.info("点击了等待可以点击的元素失败,通过js点击,其元素信息【"+element.toString()+"】"); clickByJs(element); } catch (Exception e2) { e.printStackTrace(); } } } /** * 点击某个元素 * @param expectedPageKeyword 预期页面 * @param expectedUIElementKeyword 预期关键字 */ public static void click(String expectedPageKeyword,String expectedUIElementKeyword ) { try { logger.info("点击了【关键页面】:【"+expectedPageKeyword+"】【关键元素】:【"+expectedUIElementKeyword+"】"); waitElementToBeClickable(expectedPageKeyword, expectedUIElementKeyword).click(); } catch (Exception e) { try { logger.info("点击了【关键页面】:【"+expectedPageKeyword+"】【关键元素】:【"+expectedUIElementKeyword+"】失败,现通过js点击"); clickByJs(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword)); } catch (Exception e2) { e.printStackTrace(); } } } /** * 输入信息 * @param locator By定位对象 * @param keysToSend 输入的值 */ public static void input(By locator,String keysToSend) { try { logger.info("对dom存在的元素进行输入,其定位信息【"+locator.toString()+"】,【输入的内容】为:【"+keysToSend+"】"); waitPresenceOfElementLocated(locator).sendKeys(keysToSend); if (!checkTextToBePresentInElementValue(locator, keysToSend)) { logger.info("对dom存在的元素进行输入,输入的信息和value值不一致,通过js直接改变value值,其定位信息【"+locator.toString()+"】,【输入的内容】为:【"+keysToSend+"】"); modifyValueByJs(waitPresenceOfElementLocated(locator), keysToSend); } } catch (Exception e) { e.printStackTrace(); } } /** * 输入信息 * @param element 元素对象 * @param keysToSend 输入的值 */ public static void input(WebElement element,String keysToSend ) { try { logger.info("对dom存在的元素进行输入,其定位信息【"+element.toString()+"】,【输入的内容】为:【"+keysToSend+"】"); element.sendKeys(keysToSend); if (!checkTextToBePresentInElementValue(element, keysToSend)) { logger.info("对dom存在的元素进行输入,输入的信息和value值不一致,通过js直接改变value值,其定位信息【"+element.toString()+"】,【输入的内容】为:【"+keysToSend+"】"); modifyValueByJs(element, keysToSend); } } catch (Exception e) { e.printStackTrace(); } } /** * 点击某个元素 * @param expectedPageKeyword 预期页面 * @param expectedUIElementKeyword 预期关键字 * @param keysToSend 输入的值 */ public static void input(String expectedPageKeyword,String expectedUIElementKeyword,String keysToSend ) { try { logger.info("向【关键页面】:【"+expectedPageKeyword+"】【关键元素】:【"+expectedUIElementKeyword+"】输入【 "+keysToSend+"】"); waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword).sendKeys(keysToSend); if (!checkTextToBePresentInElementValue(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword), keysToSend)) { logger.info("对dom存在的元素进行输入,输入的信息和value值不一致,通过js直接改变value值,其关键页面【"+expectedPageKeyword+"】,【关键元素】:【"+ expectedUIElementKeyword+"】,【输入的内容】为:【"+keysToSend+"】"); modifyValueByJs(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword), keysToSend); } }catch (Exception e) { e.printStackTrace(); } } /** * 取消选择所有select * @param locator By 对象定位信息 */ public static void deselectAll(By locator) { logger.info("取消所有的select选项,select定位是:【"+locator.toString()+"】"); Select select = new Select(waitPresenceOfElementLocated(locator)); select.deselectAll(); } /** * 取消选择所有select * @param element WebElement对象 */ public static void deselectAll(WebElement element) { logger.info("取消所有的select选项,select定位是:【"+element.toString()+"】"); Select select = new Select(element); select.deselectAll(); } /** * 取消选择所有select * @param expectedPageKeyword 预期页面 * @param expectedUIElementKeyword 预期关键字 */ public static void deselectAll(String expectedPageKeyword,String expectedUIElementKeyword) { logger.info("取消所有的select选项"); Select select = new Select(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword)); select.deselectAll(); } /** * 通过索引来选择select * @param locator By 对象定位信息 * @param index 索引 */ public static void selectByIndex(By locator,int index) { logger.info("通过索引来选择select,select定位是:【"+locator.toString()+"】,【索引值】:【"+index+"】"); Select select = new Select(waitPresenceOfElementLocated(locator)); select.selectByIndex(index); } /** * 通过索引来选择select * @param element WebElement对象 * @param index 索引 */ public static void selectByIndex(WebElement element,int index) { logger.info("通过索引来选择select,select定位是:【"+element.toString()+"】,【索引值】:【"+index+"】"); Select select = new Select(element); select.selectByIndex(index); } /** * 通过索引值来选择select * @param expectedPageKeyword 预期页面 * @param expectedUIElementKeyword 预期关键字 * @param index 索引值 */ public static void selectByIndex(String expectedPageKeyword,String expectedUIElementKeyword,int index) { logger.info("通过索引值来选择select,select所在关键页面是:【"+expectedPageKeyword+"】,所在关键元素是【"+expectedUIElementKeyword+"】,【索引值】:【"+index+"】"); Select select = new Select(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword)); select.selectByIndex(index); } /** * 通过value值来选择select * @param locator By 对象定位信息 * @param value value值 */ public static void selectByValue(By locator,String value) { logger.info("通过value值来选择select,select定位是:【"+locator.toString()+"】,【value值值】:【"+value+"】"); Select select = new Select(waitPresenceOfElementLocated(locator)); select.selectByValue(value); } /** * 通过value值来选择select * @param element WebElement对象 * @param value value值 */ public static void selectByValue(WebElement element,String value) { logger.info("通过value值来选择select,select定位是:【"+element.toString()+"】,【value值值】:【"+value+"】"); Select select = new Select(element); select.selectByValue(value); } /** * 通过value值来选择select * @param expectedPageKeyword 预期页面 * @param expectedUIElementKeyword 预期关键字 * @param value value值 */ public static void selectByValue(String expectedPageKeyword,String expectedUIElementKeyword,String value) { logger.info("通过value值来选择select,select所在关键页面是:【"+expectedPageKeyword+"】,所在关键元素是【"+expectedUIElementKeyword+"】,【value值值】:【"+value+"】"); Select select = new Select(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword)); select.selectByValue(value); } // /** * 通过可见文本值来选择select * @param locator By 对象定位信息 * @param text 可见文本值 */ public static void selectByVisibleText(By locator,String text) { logger.info("通过可见文本值来选择select,select定位是:【"+locator.toString()+"】,【可见文本值】:【"+text+"】"); Select select = new Select(waitPresenceOfElementLocated(locator)); select.selectByVisibleText(text); } /** * 通过可见文本值来选择select * @param element WebElement对象 * @param text 可见文本值 */ public static void selectByVisibleText(WebElement element,String text) { logger.info("通过可见文本值来选择select,select定位是:【"+element.toString()+"】,【可见文本值】:【"+text+"】"); Select select = new Select(element); select.selectByVisibleText(text); } /** * 通过可见文本值来选择select * @param expectedPageKeyword 预期页面 * @param expectedUIElementKeyword 预期关键字 * @param text 可见文本值 */ public static void selectByVisibleText(String expectedPageKeyword,String expectedUIElementKeyword,String text) { logger.info("通过可见文本值来选择select,select所在关键页面是:【"+expectedPageKeyword+"】,所在关键元素是【"+expectedUIElementKeyword+"】,【可见文本值】:【"+text+"】"); Select select = new Select(waitPresenceOfElementLocated(expectedPageKeyword, expectedUIElementKeyword)); select.selectByVisibleText(text); } /** * 确认alter弹框 */ public static void acceptAlert() { logger.info("确认alter弹框"); Alert alert = getBroswer().switchTo().alert(); alert.accept(); } /** * 关闭浏览器 */ public static void closeBrowser() { logger.info("关闭浏览器"); getBroswer().quit(); } /** * 取消alter弹框 */ public static void dismissAlert() { logger.info("取消alter弹框"); Alert alert = getBroswer().switchTo().alert(); alert.dismiss(); } /** * 检查给定元素是否被选中的期望值。 * @param locator By 对象定位信息 * @param selected 预期的选中状态 * @return 返回true,实际选中状态和预期选中状态一致,反之返回false */ public static Boolean checkElementSelectionStateToBe(By locator,boolean selected) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,检查select是否被选中,【预期选中状态】:【"+selected+"】"); logger.info("返回的实际选中状态【"+ getWait().until(ExpectedConditions.elementSelectionStateToBe(locator, selected))+"】"); return getWait().until(ExpectedConditions.elementSelectionStateToBe(locator, selected)); } /** * 检查给定元素是否被选中的期望值。 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 返回true,实际选中状态和预期选中状态一致,反之返回false */ public static Boolean checkElementSelectionStateToBe(String expectedPageKeyword,String expectedUIElementKeyword,boolean selected ) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,检查select是否被选中"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,检查select是否被选中"); logger.info("返回的实际选中状态【"+ getWait().until(ExpectedConditions.elementSelectionStateToBe(locator, selected))+"】"); return getWait().until(ExpectedConditions.elementSelectionStateToBe(locator, selected)); } /** * 检查给定元素是否被选中的期望值。 * @param element 需要判断的元素 * @param selected 预期的选中状态 * @return 返回true,实际选中状态和预期选中状态一致,反之返回false */ public static Boolean checkElementSelectionStateToBe(WebElement element,boolean selected) { logger.info("获取【element元素信息】为:【"+element.toString()+"】,检查select是否被选中,【预期选中状态】:【"+selected+"】"); logger.info("返回的实际选中状态【"+ getWait().until(ExpectedConditions.elementSelectionStateToBe(element, selected))+"】"); return getWait().until(ExpectedConditions.elementSelectionStateToBe(element, selected)); } /** * 检查给定元素是否被选中。 * @param locator By 对象定位信息 * @return 已选择返回true,反之返回false */ public static Boolean checkElementToBeSelected(By locator) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,检查select被选中"); logger.info("返回的实际选中状态【"+ getWait().until(ExpectedConditions.elementToBeSelected(locator))+"】"); return getWait().until(ExpectedConditions.elementToBeSelected(locator)); } /** * 检查给定元素是否被选中。 * @param element 需要判断的元素 * @param selected 预期的选中状态 * @return 已选择返回true,反之返回false */ public static Boolean checkElementToBeSelected(WebElement element) { logger.info("获取【element元素信息】为:【"+element.toString()+"】,检查select被选中"); logger.info("返回的实际选中状态【"+ getWait().until(ExpectedConditions.elementToBeSelected(element))+"】"); return getWait().until(ExpectedConditions.elementToBeSelected(element)); } /** * 检查给定元素是否被选中。 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @return 已选择返回true,反之返回false */ public static Boolean checkElementToBeSelected(String expectedPageKeyword,String expectedUIElementKeyword ) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,检查select被选中"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,检查select被选中"); logger.info("返回的实际选中状态【"+ getWait().until(ExpectedConditions.elementToBeSelected(locator))+"】"); return getWait().until(ExpectedConditions.elementToBeSelected(locator)); } /** * 获取指定元素的实际文本,是否【等于】预期的文本值 * @param locator By 对象定位信息 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBe(By locator,String value) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,预期的文本值【"+value+"】,获取指定元素的实际文本,是否【等于】预期的文本值"); logger.info("获取【实际文本值】为:【"+waitPresenceOfElementLocated(locator).getText()+"】"); logger.info("返回的文本与预期的文本是否相等状态:【"+ getWait().until(ExpectedConditions.textToBe(locator,value ))+"】"); return getWait().until(ExpectedConditions.textToBe(locator, value)); } /** * 获取指定元素的实际文本,是否【等于】预期的文本值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBe(String expectedPageKeyword,String expectedUIElementKeyword,String value) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,获取指定元素的实际文本,是否【等于】预期的文本值"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,获取指定元素的实际文本,是否等于预期的文本值"); logger.info("获取【实际文本值】为:【"+waitPresenceOfElementLocated(locator).getText()+"】"); logger.info("返回的文本与预期的文本是否相等状态:【"+ getWait().until(ExpectedConditions.textToBe(locator,value ))+"】"); return getWait().until(ExpectedConditions.textToBe(locator, value)); } /** * 获取指定元素的实际文本,是否【包含】预期的文本值 * @param locator By 对象定位信息 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBePresentInElementLocated(By locator,String value) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,预期的文本值【"+value+"】,,获取指定元素的实际文本,是否【包含】预期的文本值"); logger.info("获取【实际文本值】为:【"+waitPresenceOfElementLocated(locator).getText()+"】"); logger.info("返回的文本与预期的文本是否【相等】状态:【"+ getWait().until(ExpectedConditions.textToBePresentInElementLocated(locator, value))+"】"); return getWait().until(ExpectedConditions.textToBePresentInElementLocated(locator, value)); } /** * 获取指定元素的实际文本,是否【包含】预期的文本值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBePresentInElementLocated(String expectedPageKeyword,String expectedUIElementKeyword,String value) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,获取指定元素的实际文本,是否【包含】等于预期的文本值"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,获取指定元素的实际文本,是否【包含】等于预期的文本值"); logger.info("获取【实际文本值】为:【"+waitPresenceOfElementLocated(locator).getText()+"】"); logger.info("返回的文本与预期的文本是否【包含】状态:【"+ getWait().until(ExpectedConditions.textToBePresentInElementLocated(locator,value ))+"】"); return getWait().until(ExpectedConditions.textToBePresentInElementLocated(locator, value)); } /** * 获取指定元素的实际文本,是否【包含】预期的文本值 * @param element 指定元素 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBePresentInElementLocated(WebElement element,String value) { logger.info("获取【element元素信息】为:【"+element.toString()+"】,预期的文本值【"+value+"】,获取指定元素的实际文本值获取指定元素的实际文本,是否【包含】等于预期的文本值"); logger.info("获取【实际文本值】为:【"+element.getText()+"】"); logger.info("返回的文本与预期的文本是否【包含】状态:【"+ getWait().until(ExpectedConditions.textToBePresentInElement(element, value))+"】"); return getWait().until(ExpectedConditions.textToBePresentInElement(element, value)); } /** * 获取指定元素的实际value属性值,是否【包含】预期的value属性值 * @param element 指定元素 * @param value 预期value * @return 等于返回true,反之返回false */ public static Boolean checkTextToBePresentInElementValue(WebElement element,String value) { logger.info("获取【element元素信息】为:【"+element.toString()+"】,预期的value值【"+value+"】,获取指定元素的实际value值获取指定元素的实际文本,是否【包含】等于预期的value值"); logger.info("获取【实际value值】为:【"+element.getAttribute("value")+"】"); logger.info("返回的文本与预期的文本是否【包含】状态:【"+ getWait().until(ExpectedConditions.textToBePresentInElementValue(element, value))+"】"); return getWait().until(ExpectedConditions.textToBePresentInElementValue(element, value)); } /** * 获取指定元素的实际value属性值,是否【包含】预期的value属性值 * @param locator By 对象定位信息 * @param value 预期value值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBePresentInElementValue(By locator,String value) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,预期的文本值【"+value+"】,获取指定元素的实际value值,获取指定元素的实际value属性值,是否【包含】等于预期的value属性值"); logger.info("获取【实际value值】为:【"+waitPresenceOfElementLocated(locator).getAttribute("value")+"】"); logger.info("返回的实际value值与预期的value值是否【包含】状态:【"+ getWait().until(ExpectedConditions.textToBePresentInElementValue(locator, value))+"】"); return getWait().until(ExpectedConditions.textToBePresentInElementValue(locator, value)); } /** * 获取指定元素的实际value属性值,是否【包含】预期的value属性值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkTextToBePresentInElementValue(String expectedPageKeyword,String expectedUIElementKeyword,String value) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,【预期的属性值】:【"+value+"】获取指定元素的实际value属性值,是否【包含】等于预期的value属性值"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,获取指定元素的实际value属性值,是否【包含】等于预期的value属性值"); logger.info("获取【实际value值】为:【"+waitPresenceOfElementLocated(locator).getAttribute("value")+"】"); logger.info("返回的实际value值与预期的value值是否【包含】状态:【"+ getWait().until(ExpectedConditions.textToBePresentInElementValue(locator,value ))+"】"); return getWait().until(ExpectedConditions.textToBePresentInElementValue(locator, value)); } /** * 获取指定元素的实际属性,是否【包含】预期的属性值 * @param element 指定元素 * @param attribute 指定属性名 * @param value 预期value * @return 等于返回true,反之返回false */ public static Boolean checkAttributeContains(WebElement element,String attribute,String value) { logger.info("获取【element元素信息】为:【"+element.toString()+"】,指定的【属性名】:【"+attribute+"】,【预期的属性值】:"+value+",获取指定元素的实际属性是否【包含】等于预期的属性值"); logger.info("获取【实际属性值】为:【"+element.getAttribute(attribute)+"】"); logger.info("返回的文本与预期的文本是否【包含】状态:【"+ getWait().until(ExpectedConditions.attributeContains(element, attribute, value))+"】"); return getWait().until(ExpectedConditions.attributeContains(element, attribute, value)); } /** * 检查alter弹框是否存在 * @return true存在,false不存在 */ public boolean checkAlertIsPresent() { try { logger.info("开始检查alter是否存在"); getWait().until(ExpectedConditions.alertIsPresent()); logger.info("开始检查alter存在"); return true; }catch (Exception e) { logger.info("开始检查alter不存在"); return false; } } /** * 检查页面元素是否可见 * @param locator * @return 如果返回为true,页面不可见或者元素不再dom中,返回false,页面可见 */ public static boolean checkInvisibilityOfElementLocated(By locator) { logger.info("检查元素是否不可见或页面不存在,【元素信息】:【"+locator.toString()+"】"); logger.info("检查元素是否不可见或页面的状态:【"+getWait().until(ExpectedConditions.invisibilityOfElementLocated(locator))+"】"); return getWait().until(ExpectedConditions.invisibilityOfElementLocated(locator)); } /** * 获取指定元素的实际属性,是否【包含】预期的属性值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param attribute 指定属性名 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkAttributeContains(String expectedPageKeyword,String expectedUIElementKeyword,String attribute,String value) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,指定的【属性名】:【"+attribute+"】,【预期的属性值】:"+value+",获取指定元素的实际属性是否【包含】等于预期的属性值"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,获取指定元素的实际属性值,是否【包含】等于预期的属性值"); logger.info("获取【实际属性值】为:【"+waitPresenceOfElementLocated(locator).getAttribute(attribute)+"】"); logger.info("返回的实际属性值与预期的属性值是否【包含】状态:【"+ getWait().until(ExpectedConditions.attributeContains(locator, attribute, value))+"】"); return getWait().until(ExpectedConditions.attributeContains(locator, attribute, value)); } /** * 获取指定元素的实际属性,是否【包含】预期的属性值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param attribute 指定属性名 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkAttributeContains(By locator,String attribute,String value) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,【指定的属性名】:【"+attribute+"】,【指定的预期属性值】:【"+value+"】,获取指定元素的实际属性值,是否【包含】等于预期的属性值"); logger.info("获取【实际属性值】为:【"+waitPresenceOfElementLocated(locator).getAttribute(attribute)+"】"); logger.info("返回的实际属性值与预期的属性值是否【包含】状态:【"+ getWait().until(ExpectedConditions.attributeContains(locator, attribute, value))+"】"); return getWait().until(ExpectedConditions.attributeContains(locator, attribute, value)); } /** * 获取指定元素的实际属性,是否【等于】预期的属性值 * @param element 指定元素 * @param attribute 指定属性名 * @param value 预期value * @return 等于返回true,反之返回false */ public static Boolean checkAttributeToBe(WebElement element,String attribute,String value) { logger.info("获取【element元素信息】为:【"+element.toString()+"】,指定的【属性名】:【"+attribute+"】,【预期的属性值】:"+value+",获取指定元素的实际属性是否【等于】等于预期的属性值"); logger.info("获取【实际属性值】为:【"+element.getAttribute(attribute)+"】"); logger.info("返回的文本与预期的文本是否【等于】状态:【"+ getWait().until(ExpectedConditions.attributeToBe(element, attribute, value))+"】"); return getWait().until(ExpectedConditions.attributeToBe(element, attribute, value)); } /** * 获取指定元素的实际属性,是否【等于】预期的属性值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param attribute 指定属性名 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkAttributeToBe(String expectedPageKeyword,String expectedUIElementKeyword,String attribute,String value) { logger.info("获取【页面关键字】为:【"+expectedPageKeyword+"】,获取【元素关键字】为:【"+expectedUIElementKeyword+"】,指定的【属性名】:【"+attribute+"】,【预期的属性值】:"+value+",获取指定元素的实际属性是否【等于】等于预期的属性值"); By locator = getXmlBy(expectedPageKeyword, expectedUIElementKeyword); logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,获取指定元素的实际属性值,是否【等于】等于预期的属性值"); logger.info("获取【实际属性值】为:【"+waitPresenceOfElementLocated(locator).getAttribute(attribute)+"】"); logger.info("返回的实际属性值与预期的属性值是否【等于】状态:【"+ getWait().until(ExpectedConditions.attributeToBe(locator, attribute, value))+"】"); return getWait().until(ExpectedConditions.attributeToBe(locator, attribute, value)); } /** * 获取指定元素的实际属性,是否【等于】预期的属性值 * @param expectedPageKeyword 预期页面关键在 * @param expectedUIElementKeyword 预期元素关键字 * @param attribute 指定属性名 * @param value 预期的文本值 * @return 等于返回true,反之返回false */ public static Boolean checkAttributeToBe(By locator,String attribute,String value) { logger.info("获取【locator定位信息】为:【"+locator.toString()+"】,【指定的属性名】:【"+attribute+"】,【指定的预期属性值】:【"+value+"】,获取指定元素的实际属性值,是否【等于】等于预期的属性值"); logger.info("获取【实际属性值】为:【"+waitPresenceOfElementLocated(locator).getAttribute(attribute)+"】"); logger.info("返回的实际属性值与预期的属性值是否【等于】状态:【"+ getWait().until(ExpectedConditions.attributeToBe(locator, attribute, value))+"】"); return getWait().until(ExpectedConditions.attributeToBe(locator, attribute, value)); } // public void test() throws InterruptedException { // //把“随意拖拽1-1”元素移动到“随意拖拽1-2”节点下去 // WebElement webElement1 = BrowserUtil.driver.findElement(By.id("treeDemo_2_span")); // WebElement webElement2= BrowserUtil.driver.findElement(By.id("treeDemo_3_span")); // //构建鼠标的一连串动作 // Actions actions = new Actions(BrowserUtil.driver); // actions.clickAndHold(webElement1).moveToElement(webElement2).release().build().perform(); // } public static By getXmlBy(String path ,String expectedPageKeyword,String expectedUIElementKeyword) { try { String uiElementBy = ""; String uiElementValue = ""; for(Page page:XmlUtils.loadXml(path)) { String actualPageKeyword = page.getKeyword(); if (expectedPageKeyword.equals(actualPageKeyword)) { for (UIElement uiElement : page.getUiElementList()) { String actualUiElement = uiElement.getKeyword(); if (expectedUIElementKeyword.equals(actualUiElement)) { uiElementBy = uiElement.getBy(); uiElementValue = uiElement.getValue(); } } } } Class<By> clazz = By.class; Method method = clazz.getMethod(uiElementBy, String.class); By by =(By) method.invoke(null, uiElementValue); return by;}catch (Exception e) { e.printStackTrace(); } return null; } public static By getXmlBy(String expectedPageKeyword,String expectedUIElementKeyword) { try { String uiElementBy = ""; String uiElementValue = ""; for(Page page:XmlUtils.loadXml("")) { String actualPageKeyword = page.getKeyword(); if (expectedPageKeyword.equals(actualPageKeyword)) { for (UIElement uiElement : page.getUiElementList()) { String actualUiElement = uiElement.getKeyword(); if (expectedUIElementKeyword.equals(actualUiElement)) { uiElementBy = uiElement.getBy(); uiElementValue = uiElement.getValue(); } } } } Class<By> clazz = By.class; Method method = clazz.getMethod(uiElementBy, String.class); By by =(By) method.invoke(null, uiElementValue); return by; }catch (Exception e) { e.printStackTrace(); } return null; } //=======================================Js部分========================================================= /** * Selenium定位的元素被图层遮挡,click无法操作,可以用此方法点击 * @param webElement 需要操作的元素 */ public static void clickByJs(WebElement webElement) { logger.info(webElement.toString()); getJs().executeScript("arguments[0].click();", webElement); } /** * 去除元素只读属性 * @param webElement 需要操作的元素 */ public static void removeAttributeReadonly(WebElement webElement) { getJs().executeScript("arguments[0].removeAttribute('readonly')",webElement); } /** * 文本输入框赋值 * @param webElement 需要操作的元素 * @param input 期望输入的值 * 注意: JS企图去控制输入框的值失效,是因为没有触发input或change事件(有些前端会设置) */ public static void modifyValueByJs(WebElement webElement,String input) { getJs().executeScript("arguments[0].value=arguments[1]",webElement,input); } /** * 设置富文本框的内容 * @param webElement 需要操作的元素 * @param input 期望输入的值 */ public static void modifyInnerHTMLByJs(WebElement webElement,String input) { getJs().executeScript("arguments[0].innerHTML = arguments[1]" ,webElement,input); } /** * 利用js代码取出关键字 * @param webElement 需要操作的元素 * @return 返回获取的value值 */ public static String getValueByJs(WebElement webElement) { return (String) getJs().executeScript("var result=arguments[0].value;return result",webElement); } /** * 用js判断页面加载完毕,返回complete * @return 返回complete */ public static String judgeLoadComplete() { return getJs().executeScript("return document.readyState").toString(); } /** * 获取富文本框内容 * @param webElement 需要操作的元素 * @return 返回获取的innerHTML */ public static String getInnerHTMLByJs(WebElement webElement) { return (String) getJs().executeScript("var result=arguments[0].innerHTML;return result" ,webElement); } /** * 滑动页面到指定元素的顶部对其 * @param webElement 需要操作的元素 */ public static void scrollIntoTopView(WebElement webElement) { getJs().executeScript("arguments[0].scrollIntoView(true);",webElement); } /** * 滑动页面到指定元素的顶部底部 * @param webElement 需要操作的元素 */ public static void scrollInTobottomView(WebElement webElement) { getJs().executeScript("arguments[0].scrollIntoView(false);",webElement); } /** * 元素滚动至可见位置_如果当前可见,则不会发生滚动 * @param webElement 需要操作的元素 */ public static void scrollIntoViewIfNeeded(WebElement webElement) { getJs().executeScript("arguments[0].scrollIntoViewIfNeeded(true);",webElement); } /** * 封装设置或者新增页面对象的属性值的方法 调用JS代码修改页面元素的属性值,arguments[0]~arguments[1]分别 * 会用后面的element,attributeName和value参数进行替换 * @param webElement 需要操作的元素 * @param attributeName 属性名 * @param attributeValue 属性值 */ public static void setAttribute(WebElement webElement,String attributeName,String attributeValue) { getJs().executeScript("arguments[0].setAttribute(\""+attributeName+"\",\""+attributeValue+"\")",webElement,attributeName,attributeValue); } /** * 删除元素指定元素属性 * @param webElement 需要操作的元素 * @param attributeName 属性名 */ public static void removeAttribute(WebElement webElement,String attributeName) { getJs().executeScript("arguments[0].removeAttribute(arguments[1])",webElement,attributeName); } /** * 获取指定元素对应的属性值 * @param webElement 需要操作的元素 * @param attributeName 属性名 * @return 返回指定元素对应的属性值 */ public static String getAttribute(WebElement webElement,String attributeName) { logger.info("浏览器信息和获取的元素信息:【"+webElement.toString()+"】,获取该元素属性名为【"+attributeName+"】,属性值值为【"+(String)getJs().executeScript("return arguments[0].getAttribute(arguments[1])",webElement,attributeName)+"】"); return (String)getJs().executeScript("return arguments[0].getAttribute(arguments[1])",webElement,attributeName); } /** * 元素高亮展示 #边框border:2px; blue红色 * @param webElement 需要操作的元素 */ public static void setHighLight(WebElement webElement) { logger.info("浏览器信息和获取的元素信息:【"+webElement.toString()+"】,设置了【style】属性,其属性值为【border: 10px solid blue;】,其目的是高亮显示元素"); setAttribute(webElement, "style", "border: 10px solid blue;"); } //=======================================正则表达式替换修改xml部分=========================================== /** * 替换${格式的信息} * @param expectedPageKeyword * @param expectedUIElementKeyword * @param modifyValue */ public static void replaceValue(String expectedPageKeyword,String expectedUIElementKeyword,String modifyValue) { // XmlUtils.(expectedPageKeyword, expectedUIElementKeyword, modifyValue, "\\$\\{.+\\}"); } /** * 替换中文字符为S{XXX} * @param expectedPageKeyword * @param expectedUIElementKeyword * @param modifyValue */ public static void replaceChinese(String expectedPageKeyword,String expectedUIElementKeyword,String modifyValue) { // XmlUtil.modifyXmlInfo(expectedPageKeyword, expectedUIElementKeyword, modifyValue, "[\\x{4e00}-\\x{9fa5}]+"); } //机动车综合险2020版 /** * 将中文字符替换为 S{XXX} * @param expectedPageKeyword * @param expectedUIElementKeyword * @param modifyValue */ public static void replaceChineseNum(String expectedPageKeyword,String expectedUIElementKeyword,String modifyValue) { // XmlUtil.modifyXmlInfo(expectedPageKeyword, expectedUIElementKeyword, modifyValue, "[0-9\\x{4e00}-\\x{9fa5}]+"); } /** * 匹配中文和带-的 * @param expectedPageKeyword * @param expectedUIElementKeyword * @param modifyValue */ public static void replaceChineseNum1(String expectedPageKeyword,String expectedUIElementKeyword,String modifyValue) { // XmlUtil.modifyXmlInfo(expectedPageKeyword, expectedUIElementKeyword, modifyValue, "[\\\\-\\x{4e00}-\\x{9fa5}]+"); } }
package Exceptions; public class regexMatchException extends Exception{ public regexMatchException() { super(); // TODO Auto-generated constructor stub } public regexMatchException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } public regexMatchException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public regexMatchException(String message) { super(message); // TODO Auto-generated constructor stub } public regexMatchException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } public static void main(String[] args) throws regexMatchException { int i =1; if (2>i) { throw new regexMatchException("匹配到的内容不符合!"); } } }
package listener; import java.io.File; import java.io.IOException; import org.apache.log4j.Logger; import org.testng.IHookCallBack; import org.testng.IHookable; import org.testng.ITestResult; import com.google.common.io.Files; import utils.BrowserUtils; import utils.ExceptionUtil; import io.qameta.allure.Attachment; public class AllureReportListener implements IHookable{ private final static Logger logger = Logger.getLogger(AllureReportListener.class); public void run(IHookCallBack callBack, ITestResult testResult) { //1、执行test方法 //testResult-->测试结果 callBack.runTestMethod(testResult); //2、判断测试结果是否有异常 if(testResult.getThrowable() != null){ try { //发生了异常-->调用截图的方法 //把截图嵌入到Allure报表中 saveScreenshot(); Exception e = (Exception) testResult.getThrowable() ; logger.error("error:"+ ExceptionUtil.getStringExceptionStack(e)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Attachment(value = "Page screenshot", type = "image/png") public byte[] saveScreenshot() throws IOException { //怎么样获取到项目的根目录 String projectDir= System.getProperty("user.dir"); //截图文件名字 String fileName = System.currentTimeMillis()+".png"; File file = BrowserUtils.takeScreenShot(projectDir+"\\target\\screenshot\\"+fileName); //toByteArray静态方法,可以把file对象转换成字节数组 return Files.toByteArray(file); } }
package listener; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.testng.IAnnotationTransformer; import org.testng.IRetryAnalyzer; import org.testng.annotations.ITestAnnotation; /** *IAnnotationTransformer :动态修改所有@test注解所对应的属性 * retryAnalyzer */ public class RetryListener implements IAnnotationTransformer{ public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { //1、拿到@test注解的retryAnalyzer属性对象 IRetryAnalyzer iRetryAnalyzer = annotation.getRetryAnalyzer(); //2、如果@test的retryAnalyzer属性没有设置,iRetryAnalyzer-->null if(iRetryAnalyzer == null){ annotation.setRetryAnalyzer(TestngRetry.class); } } }
package listener; import org.apache.log4j.Logger; import org.testng.IRetryAnalyzer; import org.testng.ITestResult; public class TestngRetry implements IRetryAnalyzer { //重试机制次数限制 private int maxRetryCount = 2; //当前正在重试次数 private int currentRetryCount=0; private Logger logger =Logger.getLogger(TestngRetry.class); public boolean retry(ITestResult result) { //如果retry方法返回为true--》执行重试机制 //如果返回是为false --》不会去执行重试 //什么时候会运行到这里??条件-->测试用例执行失败 if(currentRetryCount < maxRetryCount){ //运行了一次重试机制之后,我们就加1 //如果运行第一次重试机制-->用例执行成功了,用例的结果是pass的 //如果运行第一次重试机制-->用例执行成功了,第二次重试机制不会运行 currentRetryCount++; logger.info("运行第【"+currentRetryCount+"】次重试机制"); return true; }else{ return false; } } }
package utils; import org.openqa.selenium.By; import common.BasePage; public class AutoItUtil { public static void main(String[] args) { BasePage.createBrowser("chrome"); BasePage.getUrl("https://www.layui.com/v1/demo/upload.html"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasePage.getBroswer().findElement(By.cssSelector("#test")).click(); handleUpload("chrome", "C:\\Users\\windows\\Desktop\\1.png",System.getProperty("user.dir")+"\\src\\test\\resources\\upload.exe"); } /* * 上传文件 * 普通上传:普通的附件上传是将本地文件的路径作为i一个值放在input标签中,通过form表单将这个值提交给服务器 */ //定义上传函数,第一个参数browser是浏览器的名字,第二个参数filePath是文件路径 public static void handleUpload(String browser,String filePath,String executeFile) { //定义了autoit.ext文件的路径 String executeFile1 = System.getProperty("user.dir")+ executeFile; String cmd = "\""+ executeFile+ "\""+ " "+ "\""+ browser+ "\""+ " "+ "\""+ filePath+ "\""; System.out.println(cmd); try{ Process process= Runtime.getRuntime().exec(cmd); process.waitFor(); } catch(Exception e) { e.printStackTrace(); } } public static void executeCmd(String executeFile) { //定义了autoit.ext文件的路径 String executeFile1 = System.getProperty("user.dir")+ executeFile; String cmd = "\""+ executeFile1+ "\""; System.out.println(cmd); try{ Process process= Runtime.getRuntime().exec(cmd); process.waitFor(); } catch(Exception e) { e.printStackTrace(); } } }
package utils; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class BrowserUtils { private static Logger logger = Logger.getLogger(BrowserUtils.class); /** * WebDriver ThreadLocal */ private static ThreadLocal<WebDriver> wdtl = new ThreadLocal<WebDriver>(); /** * JavascriptExecutor czzz */ public static ThreadLocal<JavascriptExecutor> jetl = new ThreadLocal<JavascriptExecutor>(); /** * WebDriverWait */ public static ThreadLocal<WebDriverWait> wdwtl = new ThreadLocal<WebDriverWait>(); public static String browerName = ""; // 标记标识打开的浏览器是hub管理的还是本地端,为true表示的是hub管理的 public static boolean browserFlag = false; /** * 封装的一个浏览器打开的工具方法 * * @param browserType */ public static void openBrowser(String browserType) { browerName = browserType; if (browserType != "") { if (browserType.equals("chrome")) { // ----------------打开Chrome的代码-------------- // 设置一个全局属性webdriver.chrome.driver ,让脚本认识到chrome驱动是在哪里 System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe"); // 实例化驱动,打开浏览器-chrome // 支持chrome“无头”浏览器模式 // ChromeOptions chromeOptions = new ChromeOptions(); // chromeOptions.addArguments("headless"); browserFlag = false; WebDriver driver = new ChromeDriver(); setDriver(driver); setWebDriverWait( new WebDriverWait(getDriver(), 6)); setJavascriptExecutor((JavascriptExecutor) getDriver()); logger.info("==============打开chrome浏览器================="); } else if (browserType.equals("firefox")) { // ---------------打开firefox的代码--------------- // 设置一个全局属性webdriver.firefox.bin,让脚本认识到firefox可执行文件是再哪里 // 设置一个全局属性webdriver.gecko.driver,让脚本认识到firefox驱动再哪里 System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe"); System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver.exe"); browserFlag = false; WebDriver driver = new FirefoxDriver(); setDriver(driver); setWebDriverWait( new WebDriverWait(getDriver(), 6)); setJavascriptExecutor((JavascriptExecutor) getDriver()); logger.info("==============打开firefox浏览器================="); } else if (browserType.equals("IE")) { // -----------打开IE的代码-------------- // 给予IE浏览器额外的能力 // 1、忽略保护模式的设置 // 2、忽略掉浏览器缩放设置 DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); desiredCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); desiredCapabilities.setCapability(InternetExplorerDriver.IGNORE_ZOOM_SETTING, true); System.setProperty("webdriver.ie.driver", "src/test/resources/IEDriverServer.exe"); browserFlag = false; // 在实例化IE驱动的时候,需要把额外的配置传给IE驱动 WebDriver driver = new InternetExplorerDriver(desiredCapabilities); setDriver(driver); setWebDriverWait( new WebDriverWait(getDriver(), 6)); setJavascriptExecutor((JavascriptExecutor) getDriver()); logger.info("==============打开ie浏览器================="); } } } /** * 封装的截图的API * * @param path * 截图对应的路径 */ public static File takeScreenShot(String path) { File file = null; // 判断打开的浏览器是什么?? if (browerName.equals("chrome") & !browserFlag) { ChromeDriver chromeDriver = (ChromeDriver) getDriver(); file = chromeDriver.getScreenshotAs(OutputType.FILE); } else if (browerName.equals("firefox") & !browserFlag) { FirefoxDriver firefoxDriver = (FirefoxDriver) getDriver(); file = firefoxDriver.getScreenshotAs(OutputType.FILE); } else if (browerName.equals("ie") & !browserFlag) { InternetExplorerDriver ieDriver = (InternetExplorerDriver) getDriver(); file = ieDriver.getScreenshotAs(OutputType.FILE); } else if (browserFlag) { //如果是使用selenium grid,打开远程端浏览器,实例化为RemoteWebDriver RemoteWebDriver reDriver = (RemoteWebDriver) getDriver(); reDriver.getScreenshotAs(OutputType.FILE); } File descFile = new File(path); // FileUtils类需要引入commons.io这个依赖 // 将截图保存到本地 try { FileUtils.copyFile(file, descFile); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return descFile; } public static void closeBrowser() { logger.info("==============关闭浏览器================="); getDriver().quit(); } /** * 打开通过hub节点管理的远程端(包括本地)浏览器 * * @param browserName * @throws MalformedURLException */ public static void openRemoteBrowser(String browserName) { // 1、创建能力对象 DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); // 2、设置远程端测试的浏览器 desiredCapabilities.setBrowserName(browserName); // 3、设置hub节点的地址 String url = "http://192.168.43.91:8888/wd/hub"; // 4、实例化RemoteWebdriver对象 try { browserFlag = true; WebDriver webDriver = new RemoteWebDriver(new URL(url), desiredCapabilities); setDriver(webDriver); setWebDriverWait( new WebDriverWait(getDriver(), 6)); setJavascriptExecutor((JavascriptExecutor) getDriver()); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 从线程的ThreadLocal区域去取存放的驱动 * @return */ public static WebDriver getDriver(){ return wdtl.get(); } /**从线程的ThreadLocal区域去存放驱动 * @param driver */ public static void setDriver(WebDriver driver){ wdtl.set(driver); } public static JavascriptExecutor getJavascriptExecutor() { return jetl.get(); } public static void setJavascriptExecutor(JavascriptExecutor js) { jetl.set(js); } public static WebDriverWait getWebDriverWait() { return wdwtl.get(); } public static void setWebDriverWait(WebDriverWait wdw) { wdwtl.set(wdw); } public static void main(String[] args) { openBrowser("chrome"); } }
package utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; import pojo.Case; import pojo.WriteBack; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelUtils { /* * 根据caseId取行号 */ public static Map<String, Integer> rowIdentifierRowIndexMap = new HashMap<String, Integer>(); /* * 列名和列号的映射 */ public static Map<String, Integer> cellNameCellIndexMap = new HashMap<String, Integer>(); public static List<WriteBack> writeBacks = new ArrayList<WriteBack>(); static { loadRowIdentifierRowNumMapAndCellNameCellNumMap("src/test/resources/测试用例.xlsx","用例"); } public static void loadRowIdentifierRowNumMapAndCellNameCellNumMap(String path,String sheetName) { FileInputStream fileInputStream = null ; try { fileInputStream = new FileInputStream(new File(path)); /* * 新建一个excel工作簿 */ Workbook workbook = WorkbookFactory.create(fileInputStream); /* * 新建一个sheet表 */ Sheet sheet = workbook.getSheet(sheetName); /* * 获取第一行数据-标题行 */ Row titleRow = sheet.getRow(0); /* * 获取第一行数据最后一列的列号 */ int lastCellNum = titleRow.getLastCellNum(); /* * 循环处理每一列,取出每一列里面的字段名,保存到数组 */ String[] fields = new String[lastCellNum]; /* * 循环拿到并处理每一列 */ for (int i = 0; i < lastCellNum; i++) { /* * 根据列索引获取对应的列 */ Cell cell = titleRow.getCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK); /* * 设置列的类型为字符串 */ cell.setCellType(CellType.STRING); /* * 获取列的值 */ String titlt = cell.getStringCellValue(); titlt = titlt.substring(0, titlt.indexOf("(")); int cellIndex = cell.getAddress().getColumn(); cellNameCellIndexMap.put(titlt, cellIndex); // System.out.println("列索引:"+"【"+cellIndex+"】;"+"对应的字段值:【"+titlt+"】"); } /* * 获取最后一行行索引 */ int lastRowIndex = sheet.getLastRowNum(); /* * 循环处理每一行数据,每一行对应一行case用例对象 */ for (int i = 1; i <= lastRowIndex; i++) { /* * 拿到一个数据行 */ Row dataRow = sheet.getRow(i); if ( isEmptyRow(dataRow)||dataRow == null) { continue; } /* * 根据列索引获取对应的列 */ Cell cell = dataRow.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK); /* * 设置列的类型为字符串 */ cell.setCellType(CellType.STRING); /* * 获取第一列值caseId */ String caseId = cell.getStringCellValue(); if (caseId.trim().length() == 0) { continue; } /* * 获取行索引 */ int rowIndex = dataRow.getRowNum(); rowIdentifierRowIndexMap.put(caseId, rowIndex); System.out.println("行索引:"+"【"+rowIndex+"】;"+"对应的caseId值:【"+caseId+"】"); } }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } /** * 加载excel数据 * @param <T> * @param path * @param sheetName * @param clazz * @return */ public static <T> List<T> load(String path,String sheetName,Class<T> clazz) { List<T> list = new ArrayList<T>(); FileInputStream fileInputStream = null ; try { fileInputStream = new FileInputStream(new File(path)); /* * 新建一个excel工作簿 */ Workbook workbook = WorkbookFactory.create(fileInputStream); /* * 新建一个sheet表 */ Sheet sheet = workbook.getSheet(sheetName); /* * 获取第一行数据-标题行 */ Row titleRow = sheet.getRow(0); /* * 获取第一行数据最后一列的列号 */ int lastCellNum = titleRow.getLastCellNum(); /* * 循环处理每一列,取出每一列里面的字段名,保存到数组 */ String[] fields = new String[lastCellNum]; /* * 循环拿到并处理每一列 */ for (int i = 0; i < lastCellNum; i++) { /* * 根据列索引获取对应的列 */ Cell cell = titleRow.getCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK); /* * 设置列的类型为字符串 */ cell.setCellType(CellType.STRING); /* * 获取列的值 */ String titlt = cell.getStringCellValue(); titlt = titlt.substring(0, titlt.indexOf("(")); fields[i] = titlt; } /* * 获取最后一行行索引 */ int lastRowIndex = sheet.getLastRowNum(); /* * 循环处理每一行数据,每一行对应一行case用例对象 */ for (int i = 1; i <= lastRowIndex; i++) { /* * 每循环一行准备一个对象,通过字节码创建对象 */ T obj = clazz.newInstance(); /* * 拿到一个数据行 */ Row dataRow = sheet.getRow(i); if (dataRow == null || isEmptyRow(dataRow)) { continue; } /* * 根据列索引获取对应的列 */ Cell cell = dataRow.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK); /* * 设置列的类型为字符串 */ cell.setCellType(CellType.STRING); /* * 获取第一列值caseId */ String caseId = cell.getStringCellValue(); if (caseId.trim().length() == 0) { continue; } /* * 拿到此数据行上的每一列,将数据封装到对象 */ for (int j = 0; j < lastCellNum; j++) { /* * 根据列索引获取对应的列 */ Cell cell1 = dataRow.getCell(j, MissingCellPolicy.CREATE_NULL_AS_BLANK); /* * 设置列的类型为字符串 */ cell1.setCellType(CellType.STRING); /* * 获取列的值 */ String value = cell1.getStringCellValue(); /* * 封装到对象(已经拿到属性值,通过反射放到对象) * 获取要反射的方法名 */ String methodName = "set"+fields[j]; /* * 获取要反射的方法对象 */ Method method = clazz.getMethod(methodName, String.class); /* * 完成反射调用 */ method.invoke(obj, value); } list.add(obj); } return list; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { closeInputStream(fileInputStream); } return null; } private static void closeInputStream(FileInputStream fileInputStream) { try { fileInputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 判断每行数据中的列都有数据返回true,否则返回false * @param dataRow * @return */ private static boolean isEmptyRow(Row dataRow) { /* * 获取行数据最后一列列号 */ int lastCellNum = dataRow.getLastCellNum(); for (int i = 0; i < lastCellNum; i++) { /* * 根据列索引获取对应的列 */ Cell cell = dataRow.getCell(0, MissingCellPolicy.CREATE_NULL_AS_BLANK); /* * 设置列的类型为字符串 */ cell.setCellType(CellType.STRING); /* * 获取列的值 */ String value = cell.getStringCellValue().trim(); if (value == null || value.length() == 0 ){ return true; } } return false; } public static void writeBackData(String path,String sheetName,String caseId,String cellName,String result) { FileInputStream fileInputStream = null ; FileOutputStream outputStream = null; try { fileInputStream = new FileInputStream(new File(path)); /* * 新建一个excel工作簿 */ Workbook workbook = WorkbookFactory.create(fileInputStream); /* * 新建一个sheet表 */ Sheet sheet = workbook.getSheet(sheetName); int rowNum = rowIdentifierRowIndexMap.get(caseId); Row row = sheet.getRow(rowNum); int cellNum = cellNameCellIndexMap.get(cellName); Cell cell = row.getCell(cellNum, MissingCellPolicy.CREATE_NULL_AS_BLANK); cell.setCellType(CellType.STRING); cell.setCellValue(result); outputStream = new FileOutputStream(new File(path)); workbook.write(outputStream); }catch (Exception e) { e.printStackTrace(); }finally { closeOutputStream(outputStream); closeInputStream(fileInputStream); } } public static void batchWriteBackBDatas(String path,String sheetName) { FileInputStream fileInputStream = null ; FileOutputStream outputStream = null; try { fileInputStream = new FileInputStream(new File(path)); /* * 新建一个excel工作簿 */ Workbook workbook = WorkbookFactory.create(fileInputStream); /* * 新建一个sheet表 */ Sheet sheet = workbook.getSheet(sheetName); for (WriteBack writeBack : writeBacks) { /* int rowNum = rowIdentifierRowIndexMap.get(writeBack.getCaseId()); Row row = sheet.getRow(rowNum); int cellNum = cellNameCellIndexMap.get(writeBack.getCellName()); Cell cell = row.getCell(cellNum, MissingCellPolicy.CREATE_NULL_AS_BLANK); cell.setCellType(CellType.STRING); cell.setCellValue(writeBack.getResult());*/ } outputStream = new FileOutputStream(new File(path)); workbook.write(outputStream); } catch (Exception e) { // TODO: handle exception }finally { closeOutputStream(outputStream); closeInputStream(fileInputStream); } } private static void closeOutputStream(FileOutputStream outputStream) { try { outputStream.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public static void main(String[] args) { writeBackData("src/test/resources/测试用例.xlsx","用例", "2", "Desc","zzzzzzzzzzzz"); List<Case> load = load("src/test/resources/测试用例.xlsx","用例", Case.class); for (Case case1 : load) { System.out.println(case1.toString()); } } }
package utils; import java.io.PrintWriter; import java.io.StringWriter; public class ExceptionUtil { /* * @功能说明:在日志文件中,打印异常堆栈 * @return:String */ public static String getStringExceptionStack(Throwable e) { StringWriter errorsWriter = new StringWriter(); e.printStackTrace(new PrintWriter(errorsWriter)); return errorsWriter.toString(); } }
package com.evcar.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; public class FastJsonUtils { private final static Logger logger = LoggerFactory.getLogger(FastJsonUtils.class); private static SerializeConfig config; static { config = new SerializeConfig(); config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 } private static final SerializerFeature[] features = { SerializerFeature.DisableCircularReferenceDetect,//打开循环引用检测,JSONField(serialize = false)不循环 SerializerFeature.WriteDateUseDateFormat,//默认使用系统默认 格式日期格式化 SerializerFeature.WriteMapNullValue, //输出空置字段 SerializerFeature.WriteNullListAsEmpty,//list字段如果为null,输出为[],而不是null SerializerFeature.WriteNullNumberAsZero,// 数值字段如果为null,输出为0,而不是null SerializerFeature.WriteNullBooleanAsFalse,//Boolean字段如果为null,输出为false,而不是null SerializerFeature.WriteNullStringAsEmpty//字符类型字段如果为null,输出为"",而不是null }; /** * 返回Json字符串里面包含的一个对象 * * @param jsonStr :{"city":"china","map1":[{"age":"28","name":"yys"}]} * @param list_str :map1 * @param clazz :Map.class,或者其他对象 * @param <T> :Map * @return :List<Map> */ public static final <T> List<T> json2childList(String jsonStr, String list_str, Class<T> clazz) { JSONObject jsonobj = JSON.parseObject(jsonStr); if (jsonobj == null) { return null; } Object obj = jsonobj.get(list_str); if (obj == null) { return null; } if (obj instanceof JSONArray) { JSONArray jsonarr = (JSONArray) obj; List<T> list = new ArrayList<T>(); for (int i = 0; i < jsonarr.size(); i++) { list.add(jsonarr.getObject(i, clazz)); } return list; } return null; } /** * 返回Json字符串里面包含的一个对象 * * @param jsonStr :{"department":{"id":"1","name":"生产部"},"password":"admin","username":"admin"} * @param obj_str :department * @param clazz :Map.class,或者其他对象 * @param <T> :Map * @return */ public static final <T> T json2childObj(String jsonStr, String obj_str, Class<T> clazz) { JSONObject jsonobj = JSON.parseObject(jsonStr); if (jsonobj == null) { return null; } Object obj = jsonobj.get(obj_str); if (obj == null) { return null; } if (obj instanceof JSONObject) { return jsonobj.getObject(obj_str, clazz); } else { logger.info(obj.getClass() + ""); } return null; } /** * json 转换成对象 * * @param jsonStr * @param clazz * @param <T> * @return */ public static final <T> T json2obj(String jsonStr, Class<T> clazz) { T t = null; try { t = JSON.parseObject(jsonStr, clazz); } catch (Exception e) { logger.error("json字符串转换失败!" + jsonStr, e); } return t; } /** * 对象转换成json字符串(带有格式化输出) * * @param object 要转换的对象 * @param prettyFormat 是否格式化json字符串,输出带有换行和缩进的字符串 * @return 返回一个json 字符串数组 */ public static final String obj2json(Object object, boolean prettyFormat) { return JSON.toJSONString(object, prettyFormat); } /** * 对象转换成json字符串 * * @param object 要转换的对象 * @return 返回一个json 字符串数组 */ public static final String obj2jsonByFeatures(Object object) { return JSON.toJSONString(object,config,features); } /** * 对象转换成json字符串 * * @param object 要转换的对象 * @return 返回一个json 字符串数组 */ public static final String obj2json(Object object) { return JSON.toJSONString(object,config); } /** * json 字符串转换成原始的Object对象 * * @param jsonStr * @return */ public static final Object json2obj(String jsonStr) { return JSON.parse(jsonStr); } /** * json字符串转换成list * * @param jsonStr Json字符串 * @param clazz 要转换的class * @param <T>返回的泛型类型 * @return 返回的<T>泛型类型 */ public static <T> List<T> json2List(String jsonStr, Class<T> clazz) { List<T> list = new ArrayList<T>(); try { list = JSON.parseArray(jsonStr, clazz); } catch (Exception e) { logger.error("json字符串转List失败!" + jsonStr, e); } return list; } /** * json字符串转换成Map * * @param jsonStr Json字符串 * @return Map */ public static Map<String, Object> json2Map(String jsonStr) { try { return JSON.parseObject(jsonStr, Map.class); } catch (Exception e) { logger.error("json字符串转换失败!" + jsonStr, e); } return null; } /** * json 转换成list<map> * * @param jsonString * @return */ public static List<Map<String, Object>> json2ListkeyMap(String jsonString) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); try { list = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() { }); } catch (Exception e) { logger.error("json字符串转map失败", e); } return list; } }
package utils; import java.io.UnsupportedEncodingException; import java.util.Random; public class RandomUtils { public static void main(String[] args) { System.out.println(getRandomName(true, 3));//三位数 System.out.println(getRandomName(2)); } /**方法1*/ public static String getRandomName(int len) { String randomName = ""; for (int i = 0; i < len; i++) { String str = null; int hightPos, lowPos; // 定义高低位 Random random = new Random(); hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值 lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值 byte[] b = new byte[2]; b[0] = (new Integer(hightPos).byteValue()); b[1] = (new Integer(lowPos).byteValue()); try { str = new String(b, "GBK"); // 转成中文 } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } randomName += str; } return randomName; } public static String getRandomName(boolean simple, int len) { String surName[] = { "赵","钱","孙","李","周","吴","郑","王","冯","陈","楮","卫","蒋","沈","韩","杨", "朱","秦","尤","许","何","吕","施","张","孔","曹","严","华","金","魏","陶","姜", "戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎", "鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐", "费","廉","岑","薛","雷","贺","倪","汤","滕","殷","罗","毕","郝","邬","安","常", "乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄", "和","穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧", "计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒","屈","项","祝","董","梁", "杜","阮","蓝","闽","席","季","麻","强","贾","路","娄","危","江","童","颜","郭", "梅","盛","林","***","锺","徐","丘","骆","高","夏","蔡","田","樊","胡","凌","霍", "虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应","宗", "丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚", "程","嵇","邢","滑","裴","陆","荣","翁","荀","羊","於","惠","甄","麹","家","封", "芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓", "牧","隗","山","谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫", "宁","仇","栾","暴","甘","斜","厉","戎","祖","武","符","刘","景","詹","束","龙", "叶","幸","司","韶","郜","黎","蓟","薄","印","宿","白","怀","蒲","邰","从","鄂", "索","咸","籍","赖","卓","蔺","屠","蒙","池","乔","阴","郁","胥","能","苍","双", "闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍", "郤","璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","郏","浦","尚","农", "温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习","宦","艾","鱼","容", "向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘", "匡","国","文","寇","广","禄","阙","东","欧","殳","沃","利","蔚","越","夔","隆", "师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空", "曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红", "游","竺","权","逑","盖","益","桓","公","晋","楚","阎","法","汝","鄢","涂","钦", "岳","帅","缑","亢","况","后","有","琴","商","牟","佘","佴","伯","赏","墨","哈", "谯","笪","年","爱","阳","佟"}; String doubleSurName[] = {"万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方", "赫连","皇甫","尉迟","公羊","澹台","公冶","宗政","濮阳","淳于","单于","太叔","申屠", "公孙","仲孙","轩辕","令狐","锺离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空", "丌官","司寇","仉","督","子车","颛孙","端木","巫马","公西","漆雕","乐正","壤驷","公良", "拓拔","夹谷","宰父","谷梁","段干","百里","东郭","南门","呼延","归","海","羊舌","微生", "梁丘","左丘","东门","西门","南宫"}; String[] word = {"一","乙","二","十","丁","厂","七","卜","人","入","八","九","几","儿","了","力","乃","刀","又", "三","于","干","亏","士","工","土","才","寸","下","大","丈","与","万","上","小","口","巾","山", "千","乞","川","亿","个","勺","久","凡","及","夕","丸","么","广","亡","门","义","之","尸","弓", "己","已","子","卫","也","女","飞","刃","习","叉","马","乡","丰","王","井","开","夫","天","无", "元","专","云","扎","艺","木","五","支","厅","不","太","犬","区","历","尤","友","匹","车","巨", "牙","屯","比","互","切","瓦","止","少","日","中","冈","贝","内","水","见","午","牛","手","毛", "气","升","长","仁","什","片","仆","化","仇","币","仍","仅","斤","爪","反","介","父","从","今", "凶","分","乏","公","仓","月","氏","勿","欠","风","丹","匀","乌","凤","勾","文","六","方","火", "为","斗","忆","订","计","户","认","心","尺","引","丑","巴","孔","队","办","以","允","予","劝", "双","书","幻","玉","刊","示","末","未","击","打","巧","正","扑","扒","功","扔","去","甘","世", "古","节","本","术","可","丙","左","厉","右","石","布","龙","平","灭","轧","东","卡","北","占", "业","旧","帅","归","且","旦","目","叶","甲","申","叮","电","号","田","由","史","只","央","兄", "叼","叫","另","叨","叹","四","生","失","禾","丘","付","仗","代","仙","们","仪","白","仔","他", "斥","瓜","乎","丛","令","用","甩","印","乐","句","匆","册","犯","外","处","冬","鸟","务","包", "饥","主","市","立","闪","兰","半","汁","汇","头","汉","宁","穴","它","讨","写","让","礼","训", "必","议","讯","记","永","司","尼","民","出","辽","奶","奴","加","召","皮","边","发","孕","圣", "对","台","矛","纠","母","幼","丝","式","刑","动","扛","寺","吉","扣","考","托","老","执","巩", "圾","扩","扫","地","扬","场","耳","共","芒","亚","芝","朽","朴","机","权","过","臣","再","协", "西","压","厌","在","有","百","存","而","页","匠","夸","夺","灰","达","列","死","成","夹","轨", "邪","划","迈","毕","至","此","贞","师","尘","尖","劣","光","当","早","吐","吓","虫","曲","团", "同","吊","吃","因","吸","吗","屿","帆","岁","回","岂","刚","则","肉","网","年","朱","先","丢", "舌","竹","迁","乔","伟","传","乒","乓","休","伍","伏","优","伐","延","件","任","伤","价","份", "华","仰","仿","伙","伪","自","血","向","似","后","行","舟","全","会","杀","合","兆","企","众", "爷","伞","创","肌","朵","杂","危","旬","旨","负","各","名","多","争","色","壮","冲","冰","庄", "庆","亦","刘","齐","交","次","衣","产","决","充","妄","闭","问","闯","羊","并","关","米","灯", "州","汗","污","江","池","汤","忙","兴","宇","守","宅","字","安","讲","军","许","论","农","讽", "设","访","寻","那","迅","尽","导","异","孙","阵","阳","收","阶","阴","防","奸","如","妇","好", "她","妈","戏","羽","观","欢","买","红","纤","级","约","纪","驰","巡","寿","弄","麦","形","进", "戒","吞","远","违","运","扶","抚","坛","技","坏","扰","拒","找","批","扯","址","走","抄","坝", "贡","攻","赤","折","抓","扮","抢","孝","均","抛","投","坟","抗","坑","坊","抖","护","壳","志", "扭","块","声","把","报","却","劫","芽","花","芹","芬","苍","芳","严","芦","劳","克","苏","杆", "杠","杜","材","村","杏","极","李","杨","求","更","束","豆","两","丽","医","辰","励","否","还", "歼","来","连","步","坚","旱","盯","呈","时","吴","助","县","里","呆","园","旷","围","呀","吨", "足","邮","男","困","吵","串","员","听","吩","吹","呜","吧","吼","别","岗","帐","财","针","钉", "告","我","乱","利","秃","秀","私","每","兵","估","体","何","但","伸","作","伯","伶","佣","低", "你","住","位","伴","身","皂","佛","近","彻","役","返","余","希","坐","谷","妥","含","邻","岔", "肝","肚","肠","龟","免","狂","犹","角","删","条","卵","岛","迎","饭","饮","系","言","冻","状", "亩","况","床","库","疗","应","冷","这","序","辛","弃","冶","忘","闲","间","闷","判","灶","灿", "弟","汪","沙","汽","沃","泛","沟","没","沈","沉","怀","忧","快","完","宋","宏","牢","究","穷", "灾","良","证","启","评","补","初","社","识","诉","诊","词","译","君","灵","即","层","尿","尾", "迟","局","改","张","忌","际","陆","阿","陈","阻","附","妙","妖","妨","努","忍","劲","鸡","驱", "纯","纱","纳","纲","驳","纵","纷","纸","纹","纺","驴","纽","奉","玩","环","武","青","责","现", "表","规","抹","拢","拔","拣","担","坦","押","抽","拐","拖","拍","者","顶","拆","拥","抵","拘", "势","抱","垃","拉","拦","拌","幸","招","坡","披","拨","择","抬","其","取","苦","若","茂","苹", "苗","英","范","直","茄","茎","茅","林","枝","杯","柜","析","板","松","枪","构","杰","述","枕", "丧","或","画","卧","事","刺","枣","雨","卖","矿","码","厕","奔","奇","奋","态","欧","垄","妻", "轰","顷","转","斩","轮","软","到","非","叔","肯","齿","些","虎","虏","肾","贤","尚","旺","具", "果","味","昆","国","昌","畅","明","易","昂","典","固","忠","咐","呼","鸣","咏","呢","岸","岩", "帖","罗","帜","岭","凯","败","贩","购","图","钓","制","知","垂","牧","物","乖","刮","秆","和", "季","委","佳","侍","供","使","例","版","侄","侦","侧","凭","侨","佩","货","依","的","迫","质", "欣","征","往","爬","彼","径","所","舍","金","命","斧","爸","采","受","乳","贪","念","贫","肤", "肺","肢","肿","胀","朋","股","肥","服","胁","周","昏","鱼","兔","狐","忽","狗","备","饰","饱", "饲","变","京","享","店","夜","庙","府","底","剂","郊","废","净","盲","放","刻","育","闸","闹", "郑","券","卷","单","炒","炊","炕","炎","炉","沫","浅","法","泄","河","沾","泪","油","泊","沿", "泡","注","泻","泳","泥","沸","波","泼","泽","治","怖","性","怕","怜","怪","学","宝","宗","定", "宜","审","宙","官","空","帘","实","试","郎","诗","肩","房","诚","衬","衫","视","话","诞","询", "该","详","建","肃","录","隶","居","届","刷","屈","弦","承","孟","孤","陕","降","限","妹","姑", "姐","姓","始","驾","参","艰","线","练","组","细","驶","织","终","驻","驼","绍","经","贯","奏", "春","帮","珍","玻","毒","型","挂","封","持","项","垮","挎","城","挠","政","赴","赵","挡","挺", "括","拴","拾","挑","指","垫","挣","挤","拼","挖","按","挥","挪","某","甚","革","荐","巷","带", "草","茧","茶","荒","茫","荡","荣","故","胡","南","药","标","枯","柄","栋","相","查","柏","柳", "柱","柿","栏","树","要","咸","威","歪","研","砖","厘","厚","砌","砍","面","耐","耍","牵","残", "殃","轻","鸦","皆","背","战","点","临","览","竖","省","削","尝","是","盼","眨","哄","显","哑", "冒","映","星","昨","畏","趴","胃","贵","界","虹","虾","蚁","思","蚂","虽","品","咽","骂","哗", "咱","响","哈","咬","咳","哪","炭","峡","罚","贱","贴","骨","钞","钟","钢","钥","钩","卸","缸", "拜","看","矩","怎","牲","选","适","秒","香","种","秋","科","重","复","竿","段","便","俩","贷", "顺","修","保","促","侮","俭","俗","俘","信","皇","泉","鬼","侵","追","俊","盾","待","律","很", "须","叙","剑","逃","食","盆","胆","胜","胞","胖","脉","勉","狭","狮","独","狡","狱","狠","贸", "怨","急","饶","蚀","饺","饼","弯","将","奖","哀","亭","亮","度","迹","庭","疮","疯","疫","疤", "姿","亲","音","帝","施","闻","阀","阁","差","养","美","姜","叛","送","类","迷","前","首","逆", "总","炼","炸","炮","烂","剃","洁","洪","洒","浇","浊","洞","测","洗","活","派","洽","染","济", "洋","洲","浑","浓","津","恒","恢","恰","恼","恨","举","觉","宣","室","宫","宪","突","穿","窃", "客","冠","语","扁","袄","祖","神","祝","误","诱","说","诵","垦","退","既","屋","昼","费","陡", "眉","孩","除","险","院","娃","姥","姨","姻","娇","怒","架","贺","盈","勇","怠","柔","垒","绑", "绒","结","绕","骄","绘","给","络","骆","绝","绞","统","耕","耗","艳","泰","珠","班","素","蚕", "顽","盏","匪","捞","栽","捕","振","载","赶","起","盐","捎","捏","埋","捉","捆","捐","损","都", "哲","逝","捡","换","挽","热","恐","壶","挨","耻","耽","恭","莲","莫","荷","获","晋","恶","真", "框","桂","档","桐","株","桥","桃","格","校","核","样","根","索","哥","速","逗","栗","配","翅", "辱","唇","夏","础","破","原","套","逐","烈","殊","顾","轿","较","顿","毙","致","柴","桌","虑", "监","紧","党","晒","眠","晓","鸭","晃","晌","晕","蚊","哨","哭","恩","唤","啊","唉","罢","峰", "圆","贼","贿","钱","钳","钻","铁","铃","铅","缺","氧","特","牺","造","乘","敌","秤","租","积", "秧","秩","称","秘","透","笔","笑","笋","债","借","值","倚","倾","倒","倘","俱","倡","候","俯", "倍","倦","健","臭","射","躬","息","徒","徐","舰","舱","般","航","途","拿","爹","爱","颂","翁", "脆","脂","胸","胳","脏","胶","脑","狸","狼","逢","留","皱","饿","恋","桨","浆","衰","高","席", "准","座","脊","症","病","疾","疼","疲","效","离","唐","资","凉","站","剖","竞","部","旁","旅", "畜","阅","羞","瓶","拳","粉","料","益","兼","烤","烘","烦","烧","烛","烟","递","涛","浙","涝", "酒","涉","消","浩","海","涂","浴","浮","流","润","浪","浸","涨","烫","涌","悟","悄","悔","悦", "害","宽","家","宵","宴","宾","窄","容","宰","案","请","朗","诸","读","扇","袜","袖","袍","被", "祥","课","谁","调","冤","谅","谈","谊","剥","恳","展","剧","屑","弱","陵","陶","陷","陪","娱", "娘","通","能","难","预","桑","绢","绣","验","继","球","理","捧","堵","描","域","掩","捷","排", "掉","堆","推","掀","授","教","掏","掠","培","接","控","探","据","掘","职","基","著","勒","黄", "萌","萝","菌","菜","萄","菊","萍","菠","营","械","梦","梢","梅","检","梳","梯","桶","救","副", "票","戚","爽","聋","袭","盛","雪","辅","辆","虚","雀","堂","常","匙","晨","睁","眯","眼","悬", "野","啦","晚","啄","距","跃","略","蛇","累","唱","患","唯","崖","崭","崇","圈","铜","铲","银", "甜","梨","犁","移","笨","笼","笛","符","第","敏","做","袋","悠","偿","偶","偷","您","售","停", "偏","假","得","衔","盘","船","斜","盒","鸽","悉","欲","彩","领","脚","脖","脸","脱","象","够", "猜","猪","猎","猫","猛","馅","馆","凑","减","毫","麻","痒","痕","廊","康","庸","鹿","盗","章", "竟","商","族","旋","望","率","着","盖","粘","粗","粒","断","剪","兽","清","添","淋","淹","渠", "渐","混","渔","淘","液","淡","深","婆","梁","渗","情","惜","惭","悼","惧","惕","惊","惨","惯", "寇","寄","宿","窑","密","谋","谎","祸","谜","逮","敢","屠","弹","随","蛋","隆","隐","婚","婶", "颈","绩","绪","续","骑","绳","维","绵","绸","绿","琴","斑","替","款","堪","搭","塔","越","趁", "趋","超","提","堤","博","揭","喜","插","揪","搜","煮","援","裁","搁","搂","搅","握","揉","斯", "期","欺","联","散","惹","葬","葛","董","葡","敬","葱","落","朝","辜","葵","棒","棋","植","森", "椅","椒","棵","棍","棉","棚","棕","惠","惑","逼","厨","厦","硬","确","雁","殖","裂","雄","暂", "雅","辈","悲","紫","辉","敞","赏","掌","晴","暑","最","量","喷","晶","喇","遇","喊","景","践", "跌","跑","遗","蛙","蛛","蜓","喝","喂","喘","喉","幅","帽","赌","赔","黑","铸","铺","链","销", "锁","锄","锅","锈","锋","锐","短","智","毯","鹅","剩","稍","程","稀","税","筐","等","筑","策", "筛","筒","答","筋","筝","傲","傅","牌","堡","集","焦","傍","储","奥","街","惩","御","循","艇", "舒","番","释","禽","腊","脾","腔","鲁","猾","猴","然","馋","装","蛮","就","痛","童","阔","善", "羡","普","粪","尊","道","曾","焰","港","湖","渣","湿","温","渴","滑","湾","渡","游","滋","溉", "愤","慌","惰","愧","愉","慨","割","寒","富","窜","窝","窗","遍","裕","裤","裙","谢","谣","谦", "属","屡","强","粥","疏","隔","隙","絮","嫂","登","缎","缓","编","骗","缘","瑞","魂","肆","摄", "摸","填","搏","塌","鼓","摆","携","搬","摇","搞","塘","摊","蒜","勤","鹊","蓝","墓","幕","蓬", "蓄","蒙","蒸","献","禁","楚","想","槐","榆","楼","概","赖","酬","感","碍","碑","碎","碰","碗", "碌","雷","零","雾","雹","输","督","龄","鉴","睛","睡","睬","鄙","愚","暖","盟","歇","暗","照", "跨","跳","跪","路","跟","遣","蛾","蜂","嗓","置","罪","罩","错","锡","锣","锤","锦","键","锯", "矮","辞","稠","愁","筹","签","简","毁","舅","鼠","催","傻","像","躲","微","愈","遥","腰","腥", "腹","腾","腿","触","解","酱","痰","廉","新","韵","意","粮","数","煎","塑","慈","煤","煌","满", "漠","源","滤","滥","滔","溪","溜","滚","滨","粱","滩","慎","誉","塞","谨","福","群","殿","辟", "障","嫌","嫁","叠","缝","缠","静","碧","璃","墙","撇","嘉","摧","截","誓","境","摘","摔","聚", "蔽","慕","暮","蔑","模","榴","榜","榨","歌","遭","酷","酿","酸","磁","愿","需","弊","裳","颗", "嗽","蜻","蜡","蝇","蜘","赚","锹","锻","舞","稳","算","箩","管","僚","鼻","魄","貌","膜","膊", "膀","鲜","疑","馒","裹","敲","豪","膏","遮","腐","瘦","辣","竭","端","旗","精","歉","熄","熔", "漆","漂","漫","滴","演","漏","慢","寨","赛","察","蜜","谱","嫩","翠","熊","凳","骡","缩","慧", "撕","撒","趣","趟","撑","播","撞","撤","增","聪","鞋","蕉","蔬","横","槽","樱","橡","飘","醋", "醉","震","霉","瞒","题","暴","瞎","影","踢","踏","踩","踪","蝶","蝴","嘱","墨","镇","靠","稻", "黎","稿","稼","箱","箭","篇","僵","躺","僻","德","艘","膝","膛","熟","摩","颜","毅","糊","遵", "潜","潮","懂","额","慰","劈","操","燕","薯","薪","薄","颠","橘","整","融","醒","餐","嘴","蹄", "器","赠","默","镜","赞","篮","邀","衡","膨","雕","磨","凝","辨","辩","糖","糕","燃","澡","激", "懒","壁","避","缴","戴","擦","鞠","藏","霜","霞","瞧","蹈","螺","穗","繁","辫","赢","糟","糠", "燥","臂","翼","骤","鞭","覆","蹦","镰","翻","鹰","警","攀","蹲","颤","瓣","爆","疆","壤","耀", "躁","嚼","嚷","籍","魔","灌","蠢","霸","露","囊","罐"}; int surNameLen = surName.length; int doubleSurNameLen = doubleSurName.length; int wordLen = word.length; StringBuffer sb = new StringBuffer(); Random random = new Random(); if(simple){ sb.append(surName[random.nextInt(surNameLen)]); int surLen = sb.toString().length(); for (int i = 0; i < len - surLen; i++) { if(sb.toString().length() <= len){ sb.append(word[random.nextInt(wordLen)]); } } }else{ sb.append(doubleSurName[random.nextInt(doubleSurNameLen)]); int doubleSurLen = sb.toString().length(); for (int i = 0; i < len - doubleSurLen; i++) { if(sb.toString().length() <= len){ sb.append(word[random.nextInt(wordLen)]); } } } return sb.toString(); } }
package utils; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import Exceptions.regexMatchException; public class RegexUtils { private static final Logger logger = Logger.getLogger(XmlUtils.class); /** * 通过正则表达式匹配需要得到的多个值 * @param regex 正则表达式 * @param input 被匹配的值 * @return 正则表达式匹配到的多个值,返回列表 * @throws Exception */ public static ArrayList<String> regexServalMatch(String regex,String input) throws Exception { logger.info("================================开始正则表达式匹配 ========================================"); logger.info("【需要被匹配到的值】:【"+input+"】,"+"【正则表达式】:【"+regex+"】"); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); ArrayList<String> results = new ArrayList<String>(); while(matcher.find()){ System.out.println(matcher.group()); results.add(matcher.group()); } if (results.size()<1) { throw new regexMatchException("返回的结果列表为空,没有匹配到数据"); }else { logger.info("【匹配得到的值】:【"+results.toString()+"】"); logger.info("================================结束正则表达式匹配 ========================================"); return results; } } /** * 通过正则表达式匹配需要得到的唯一值 * @param regex 正则表达式 * @param input 被匹配的值 * @return 正则表达式匹配到的唯一值 * @throws Exception */ public static String regexSingleMatch(String regex,String input) throws Exception { logger.info("================================开始正则表达式匹配 ========================================"); logger.info("【需要被匹配到的值】:【"+input+"】,"+"【正则表达式】:【"+regex+"】"); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); ArrayList<String> results = new ArrayList<String>(); while(matcher.find()){ System.out.println(matcher.group()); results.add(matcher.group()); } if (results.size()==1) { logger.info("【匹配得到的值】:【"+results.get(0).trim()+"】"); logger.info("================================结束正则表达式匹配 ========================================"); return results.get(0).trim(); }else { throw new regexMatchException("返回的结果列表的长度不为1,匹配错误"); } } /** * 获取通过正则表达式匹配需要得到的值的个数 * @param regex 正则表达式 * @param input 被匹配的值 * @return */ public static int getRegexMatchCount(String regex,String input) { logger.info("================================开始获取正则表达式匹配值的个数 ========================================"); logger.info("【需要被匹配到的值】:【"+input+"】,"+"【正则表达式】:【"+regex+"】"); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input); ArrayList<String> results = new ArrayList<String>(); int count = 0; while(matcher.find()){ count += 1; results.add(matcher.group()); } logger.info("【匹配得到的值个数】:【"+count+"】"); logger.info("================================结束获取正则表达式匹配值的个数 ========================================"); return count; } }
package utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class TxtUtil { /** * 鍐欏叆鏁版嵁 * @param datas 闇?瑕佸啓鍏ョ殑鏁版嵁 */ public static void write(String datas ) { File file =new File("src/main/resources/1.txt"); FileWriter fw; try { fw = new FileWriter(file,true); BufferedWriter bw =new BufferedWriter(fw); bw.write(datas+"\n"); bw.close(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 鍐欏叆鏁版嵁 * @param datas 鍐欏叆鐨勬暟鎹? * @param caseDesc 鐢ㄤ緥鎻忚堪鐨勬枃浠跺悕 */ public static void write(String datas,String caseDesc ) { File file =new File("src/main/resources/"+caseDesc+".txt"); FileWriter fw; try { fw = new FileWriter(file,true); BufferedWriter bw =new BufferedWriter(fw); bw.write(datas+"\n"); bw.close(); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 娓呯┖鏂囦欢鍐呭 * @param fileName */ public static void clearInfoForFile(String caseDesc) { File file =new File("src/main/resources/"+caseDesc+".txt"); try { if(!file.exists()) { file.createNewFile(); } FileWriter fileWriter =new FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 娓呯┖鏂囦欢鍐呭 * @param fileName */ public static void clearInfoForFile() { File file =new File("src/main/resources/1.txt"); try { if(!file.exists()) { file.createNewFile(); } FileWriter fileWriter =new FileWriter(file); fileWriter.write(""); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public static ArrayList readText() { ArrayList<Map<String, String>> arrayList = new ArrayList<Map<String,String>>(); try { File file = new File("src/main/resources/1.txt"); InputStreamReader inputReader = new InputStreamReader(new FileInputStream("src/main/resources/1.txt"),"UTF-8"); BufferedReader bf = new BufferedReader(inputReader); // 鎸夎璇诲彇瀛楃涓? String str; while ((str = bf.readLine()) != null) { Map<String, String> map = new HashMap<String, String>(); // System.out.println(str.toString().split(" ")[0].trim()+" "+ str.toString().split(" ")[1].trim()); map.put(str.toString().split( " ")[0].trim(), str.toString().split(" ")[1].trim()); arrayList.add(map); } bf.close(); inputReader.close(); return arrayList; } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) { ArrayList readText = TxtUtil.readText(); for (Object object : readText) { System.out.println(object); } } }
package utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import pojo.Page; import pojo.UIElement; public class XmlUtils { /** * 匹配${XXX}的正则表达式 */ private static final String REPLACE_VARIABLE = "\\$\\{.+\\}"; /** * 匹配中文的正则表达式 */ private static final String REPLACE_CHINESE = "[\\x{4e00}-\\x{9fa5}]+"; private static final Logger logger = Logger.getLogger(XmlUtils.class); /** * 读取xml信息 * @param path * @return */ public static ArrayList<Page> loadXml(String path) { logger.info("================================开始读取【"+path+"】元素定位信息文件中数据 ========================================"); SAXReader reader = new SAXReader(); ArrayList<Page> wantPageList = new ArrayList<Page>(); try { Document document = reader.read(new FileInputStream(new File(path))); Element rootElement = document.getRootElement(); List<Element > pageList = rootElement.elements("Page"); for (Element page : pageList) { String pageKeyword = page.attributeValue("keyword"); List<Element> uiElementList = page.elements("UIElement"); ArrayList<UIElement> wantUiElementList = new ArrayList<UIElement>(); for (Element element : uiElementList) { String uiElementKeyword = element.attributeValue("keyword"); String uiElementBY = element.attributeValue("by"); String uiElementValue = element.attributeValue("value"); UIElement uiElement = new UIElement(uiElementKeyword, uiElementBY, uiElementValue); wantUiElementList.add(uiElement); } Page pageObj = new Page(pageKeyword, wantUiElementList); wantPageList.add(pageObj); logger.info(pageObj.toString()); } logger.info("================================结束读取【"+path+"】元素定位信息文件中数据 ========================================"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return wantPageList; } /** * * 修改xml信息,根据页面关键字和元素关键字来通过正则表达式匹配到的被替换值被期待的值 * @param path 需要替换的文件路径 * @param expectedPageKeyword 预期页面关键字 * @param expectedUiElementKeyword 预期元素关键字 * @param modifyValue 替换的值 * @param reg 被替换的值-- 用正则表达式 */ public static void modifyXmlInfo(String path,String expectedPageKeyword,String expectedUiElementKeyword,String modifyValue,String reg ) { logger.info("================================开始替换【"+path+"】元素定位信息文件中数据 ========================================"); logger.info( "修改的【关键页面】:【"+expectedPageKeyword+"】,"+ "修改的【关键元素】:【"+expectedUiElementKeyword+"】," + "【被替换的值】-正则表达式【"+reg+ "】,"+ "【替换的值】为【"+modifyValue+"】"); SAXReader reader = new SAXReader(); try { Document document = reader.read(new FileInputStream(new File(path))); Element rootElement = document.getRootElement(); List<Element > pageList = rootElement.elements("Page"); for (Element page : pageList) { String pageKeyword = page.attributeValue("keyword"); if (pageKeyword.contentEquals(expectedPageKeyword)) { List<Element> uiElementList = page.elements("UIElement"); for (Element element : uiElementList) { String uiElementKeyword = element.attributeValue("keyword"); if (uiElementKeyword.equals(expectedUiElementKeyword)) { Attribute nameAttr = element.attribute("value"); String uiElementValue = element.attributeValue("value"); String text = RegexUtils.regexSingleMatch(reg, uiElementValue).trim(); String replace = uiElementValue.replace(text, modifyValue); nameAttr.setValue(replace); logger.info( "【被替换的值】为【"+text+"】-正则表达式【"+reg+ "】,"+ "【替换的值】为【"+modifyValue+"】"); logger.info("================================结束替换【"+path+"】元素定位信息文件中数据 ========================================"); } } } } FileOutputStream out =new FileOutputStream(path); // 指定文本的写出的格式: OutputFormat format=OutputFormat.createPrettyPrint(); //1.创建写出对象 XMLWriter writer=new XMLWriter(out,format); //2.写出Document对象 writer.write(document); //3.关闭流 writer.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }