数据和脚本分离之读取properties文件

为了方便管理测试数据,需要将数据和脚本分离,独立来管理数据。其中一个方法我们可以通过读取properties文件或是excel文件来读取测试数据

1.properties文件内容都是以键值对形式存在的,在工程文件下建立一个properties文件


properties文件.jpg

2.创建读取properties文件的java类

public class PropertyReader {
// 导入文件
    private static Properties props = new Properties();
    public static void init(String file) throws AssertionError{
        try {
            props.load(new FileInputStream(file));
        } catch (Exception e) {
            try {
                props.load(props.getClass().getResourceAsStream(file));

            } catch (FileNotFoundException e1) {
                throw new AssertionError("File with locator's information not found: " + e.toString());
            } catch (IOException e1) {
                throw new AssertionError("IO error while trying to reach locator's information file: " + e.toString());
            } catch (Exception ex) {
                try {
                    props.load(Reflection.getCallerClass(3).getResourceAsStream(file));
                } catch (Exception e1) {
                    throw new AssertionError("Unknown exception when calling throw Reflection: " + e1.toString());
                }
            }
        }
    }
// 获取属性值
    public static String getProperty(String key) {
        return props.getProperty(key);
    }

    public static Properties getProps() {
        return props;
    }
}

3.创建一个测试类读取properties文件,利用参数传值,运行

public class test {
    
    @Test
    public void test(){
        String path = System.getProperty("user.dir");
        String file = path + "/src/test/java/Data/data.properties";
        PropertyReader.init(file);
        driver = SeleniumDriver.openBrowser("firefox", "http://www.epwk.us/");
        Action.click(LoginPage.loginButton);
//        输入账号密码登陆
        Action.sendkeys(LoginPage.account, PropertyReader.getProperty("account"));
        Action.sendkeys(LoginPage.password, PropertyReader.getProperty("password"));
        Action.click(LoginPage.submintButton);
    }
}

利用这个有个弊端就是每次传入的值都要写对应的key,很繁琐

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,694评论 0 4
  • 转自:http://www.linuxidc.com/Linux/2011-05/35723.htm 你是否遇到过...
    Devid阅读 1,562评论 6 3
  • 关于什么是文化,我最最欣赏的回答,是作家梁晓声的四句概括:根植于内心的修养;无需提醒的自觉;以约束为前提的自由;为...
    Sherry晓阅读 468评论 0 5