android中单元测试及.properties文件的使用

项目中常常会有一些配置,除了将其写在一个常量类中外,写在配置文件中也是一种不错的选择,下面先介绍下,如何使用properties文件

java中有一个 Properties类,该类有一个方法,从一个流中加载文件

 /**

     * Loads properties from the specified {@code InputStream}, assumed to be ISO-8859-1.

     * See "<a href="#character_encoding">Character Encoding</a>".

     *

     * @param in the {@code InputStream}

     * @throws IOException

     */

    public synchronized void load(InputStream in) throws IOException {

        if (in == null) {

            throw new NullPointerException("in == null");

        }

        load(new InputStreamReader(in, "ISO-8859-1"));

    }


我们可以通过这种方法加载一个.properyies文件,下面假如我们将congfig.properties文件放在src目录下


可以通过下面的工具类来获取一个properties对象:

public class Utils {   

    /**  

     * 得到config.properties配置文件中的所有配置属性  

     *   

     * @return Properties对象  

     */  

    public static Properties getNetConfigProperties() {   

        Properties props = new Properties();   

        InputStream in = Utils.class.getResourceAsStream("/config.properties");   

        try {   

            props.load(in);   

        } catch (IOException e) {   

            e.printStackTrace();   

        }   

        return props;   

    }   

}

下面演示单元测试的配置:

在AndroidManifest.xml中配置如下:

<application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >


.....

<!-- 加入单元测试 -->

        <uses-library android:name="android.test.runner" /> 

</application>


<!-- 代表把单元测试框架中的一些依赖库引入进来 -->

<instrumentation  

        android:name="android.test.InstrumentationTestRunner"  

        android:label="Test for my app"  

        android:targetPackage="com.example.testpropertyfile"/>


这里targetPackage是你的应用包名


事例包结构如下:

com/example/testpropertyfile/junit
com/example/testpropertyfile/test01

在junit包下新建一个类 继承 AndroidTestCase如下:

public class TestPropUtilsTest extends AndroidTestCase{


public void testPropUtils(){

Properties properties = Utils.getNetConfigProperties();

System.out.println(properties.getProperty("IP"));

Log.i("szm--", properties.getProperty("IP"));

}

}


点击方法名,右键,run as Android Junit TestCase



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值