JAVA的Proxy动态代理在自动化测试中的应用

转载地址:http://www.cnblogs.com/zhangfei/p/5180197.html


JAVA的动态代理,在MYBATIS中应用的很广,其核心就是写一个interface,但不写实现类,然后用动态代理来实例化并执行这个interface中的方法,话不多说,来看一个实现的例子:

1.先定义一个接口:

1
2
3
4
5
public interface TestProxy {
     
    String hello();
     
}

 2.虽然不写实现类,但我们仍然希望在执行这个hello()方法时,能输出我们想要输出的内容,比如我把希望要输出的内容放在一个属性文件中:

1
hello=world

 我希望在调用hello方法时,输出world,接下来得解析这个属性文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class PropertiesHandler {
     
     
    privatestatic Properties p = new Properties();
     
    static{
        try{
            InputStream in =new FileInputStream(newFile("src/test.properties"));
            p.load(in);
            in.close();
        }catch (IOException e) {
            thrownew RuntimeException("test.properties load error!");
        }
    }
     
    publicstatic String getProperty(String key){
        try{
            returnp.getProperty(key, null);
        }catch(Exception e){
            e.printStackTrace();
        }
        return"";
    }
     
}

 3.解析完后,我们再写一个动态代理类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class ProxyImp<T> implementsInvocationHandler{
     
    privateClass<T> proxyMethod;
 
    publicProxyImp(Class<T> proxyMethod) {
        this.proxyMethod = proxyMethod;
    }
 
    @Override
    publicObject invoke(Object proxy, Method method, Object[] args)throwsThrowable {
        String value = PropertiesHandler.getProperty(method.getName());
        System.out.println(value);
        returnnull;
    }
 
}

 其原理就是在调用接口类方法时,动态代理类都会去执行这个invoke方法,以达到执行的目的,可以看到,在invoke方法里,我们把hello方法在属性文件中对应的值给取出来了,并输出。

4.接下来就是再封装一个代理工厂类来产生这个接口的一个实例:

1
2
3
4
5
6
7
8
9
10
11
12
public class ProxyImpFactory{
     
    @SuppressWarnings("unchecked")
    publicstatic <T> T newInstance(Class<T> methodInterface) {
        finalProxyImp<T> proxyImp = newProxyImp<T>(methodInterface);
        return(T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                newClass[]{methodInterface},
                proxyImp);
    }
 
     
}

 可以从上面的代码中看出这个代理类会自动的生成一个接口实现类的实例。

5.接下来就是真正的调用了:

1
2
3
4
public static void main(String[] args) {
    TestProxy tp = ProxyImpFactory.newInstance(TestProxy.class);
    tp.hello();
}

 输出就是:world.

6.动态代理在自动化中的作用:

 自动化中,当把元素对象用外部文件,把数据文件用外部文件时,都可以用这种方式来进行封装,其在自动化测试中最大的作用,我想就是利用在封装关键字上了,把关键字与具体的方法对应起来,就可以用这样的方式。

 至于具体的关键字的实现,我想得靠大家自已了,有兴趣的可以与我讨论!

点亮测试人生!QQ:408129370

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值