关于单元测试是开发中特别是网络编程中离不开的一个方法与工具,怎样充分的用好它显得尤其重要。
下面就针对这个方法做一些相关的说明与尝试。
第一步创建程序
第二步创建test根目录文件夹
设置TestsourcesRoot,大概应该是这个样子操作
第三步创建相关包及相关类
为什么要创建两个包呢?
第四步开始编写类
在com.mxl.mxlapp包文件下创建一个aboutTestCalss类,并添加一个sayHello()方法。
- package com.mxl.mxlapp;
- public class aboutTestClass {
- public aboutTestClass(){
- }
- public String sayHello(){
- return "hello";
- }
- }
在Common包文件下创建MyTestCommon类,并添加两个简单的方法postUrl()和getUrl();
- package Common;
- public class MyTestCommon {
- public String postUrl(){
- return "www.baidu.com";
- }
- public String getUrl(){
- return "www.12306.cn";
- }
- }
第五步关联测试类
这次要使用Ctrl+shift+T快捷键
分别打开上述的类,使用Ctrl+shift+T快捷键,将出现以下界面
点击进入以下界面
common下的类同样道理:
以上操作完成之后在test根目录下会出现以下界面:
而下面两个测试类里面的代码如下
- package com.mxl.mxlapp;
- import junit.framework.TestCase;
- import org.junit.Before;
- import org.junit.Test;
- import static org.junit.Assert.*;
- public class aboutTestClassTest extends TestCase {
- private aboutTestClass mAboutTestClass;
- @Before
- public void setUp() throws Exception {
- mAboutTestClass=new aboutTestClass();
- }
- @Test
- public void testSayHello() throws Exception {
- assertEquals("hello",mAboutTestClass.sayHello());
- }
- }
- package Common;
- import junit.framework.TestCase;
- import org.junit.Before;
- import org.junit.Test;
- import static org.junit.Assert.*;
- public class MyTestCommonTest extends TestCase {
- private MyTestCommon myTestCommon;
- @Before
- public void setUp() throws Exception {
- myTestCommon = new MyTestCommon();
- }
- @Test
- public void testPostUrl() throws Exception {
- assertEquals("www.dxy.cn", myTestCommon.postUrl());
- }
- @Test
- public void testGetUrl() throws Exception {
- assertEquals("www.dxy.cn", myTestCommon.getUrl());
- }
- }
最后
以上完成之后,还有一关键步骤需要配置,就是AndroidMainfest.xml文件下的相关操作
- <uses-permission android:name="android.permission.RUN_INSTRUMENTATION" />
- <instrumentation android:name="android.test.InstrumentationTestRunner"
- android:targetPackage="com.mxl.mxlapp"/>
- <application
- android:name=".MyApplication"
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name">
- <uses-library android:name="android.test.runner" />
- </application>
注意:Android:targetPackage和
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.mxl.mxlapp"
- android:versionCode="1"
- android:versionName="1.0" >
相同就行。这时已经配置完成了。
最后一步运行测试方法可以借助快捷键ctrl+shift+F10运行
此时显示测试已经通过。
左边栏显示ok的表示运行正确,如果有感叹号的证明和自己期望的值不相同。
问题:
为什么要创建两个包?
创建两个包对后面执行测试类中的方法有没有什么影响?
在AndroidMainfest.xml配置文件中有没有需要特别注意的?
欢迎大家补充,提出疑问!