JAVA自定义注解在自动化测试中的使用

发表于:2015-5-28 09:59

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:张飞_    来源:51Testing软件测试网采编

  在UI自动化测试中,相信很多人都喜欢用所谓的PO模式,其中的P,也就是page的意思,于是乎,在脚本里,或者在其它的page里,会要new很多的page对象,这样很麻烦,前面我们也讲到了注解的使用,很方便,那么我们可不可以用注解来代替这个new的过程呢?只有想不到,没有办不到的,因为springMVC就是用了这个方式来IOC,当然我们也可以直接用springMVC,但这无异于用牛刀来切豆腐,还不如我们自已实现一下,顺便增加一下对注解的使用的认识,代码如下:
  1.先定义一个LoadPage的注解:
  package com.test.annotation;
  import java.lang.annotation.ElementType;
  import java.lang.annotation.Retention;
  import java.lang.annotation.RetentionPolicy;
  import java.lang.annotation.Target;
  @Target(ElementType.TYPE)
  @Retention(RetentionPolicy.RUNTIME)
  public @interface LoadPage {
  String value();
  }
  2.再来实现一下这个注解:
package com.test.annotation;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;
public class LoadAllPage {
public final String basePath = "com.test";
private final String binPath = "bin";
private List<String> allClass = new ArrayList<String>();
private WebDriver driver;
public void setDriver(WebDriver driver) {
this.driver = driver;
}
public void loadAllPage(){
this.listAllFiles(binPath+File.separator+basePath.replace(".","/"));
this.getPageInstance();
}
private void listAllFiles(String path){
path = path.replace("\\", "/");
File file = new File(path);
if(file.isFile() && file.getName().endsWith(".class")){
String filePath = file.getPath().replace("\\", "/");
int startIndex = 4;
int endIndex = filePath.lastIndexOf(".class");
allClass.add(filePath.substring(startIndex, endIndex).replace("/", "."));
}else if(file.isDirectory()){
File[] files = file.listFiles();
for (File f : files) {
this.listAllFiles(f.getPath());
}
}
}
private void getPageInstance(){
for (String clazz : allClass) {
try {
Class<?> c = Class.forName(clazz);
if(c.isAnnotationPresent(LoadPage.class)){
LoadPage lp = c.getAnnotation(LoadPage.class);
Constructor<?> cons = c.getConstructor(WebDriver.class);
InitialManger.allInstance.put(lp.value(), cons.newInstance(driver));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
LoadAllPage lap = new LoadAllPage();
lap.loadAllPage();
}
}
31/3123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号