2019独角兽企业重金招聘Python工程师标准>>>

Android monkey test 脚本的编写


Instrumentation 是google开发的Android测试框架(http://developer.android.com/reference/android/test/InstrumentationTestRunner.html)

主要分为下列项目:

  • ActivityInstrumentationTestCase2

  • ActivityUnitTestCase

  • AndroidTestCase

  • ApplicationTestCase

  • InstrumentationTestCase

  • ProviderTestCase

  • ServiceTestCase

  • SingleLaunchActivityTestCase


AndroidTestCase 主要来测试相关非交互性API,比如数据库,内容提供者等,其优点是可以通过getContext获取上下文

public class TestAudio extends AndroidTestCase {      private AudioManager mAudioManager;      private boolean mUseFixedVolume;      private final static long TIME_TO_PLAY = 2000;      private final static int MP3_TO_PLAY = R.raw.testmp3;          private Context mContext;          @Override      protected void setUp() throws Exception {          // TODO Auto-generated method stub          super.setUp();                  mContext = getContext();              }            public void testmp3(){          MediaPlayer mp = MediaPlayer.create(mContext, MP3_TO_PLAY);          mp.setAudioStreamType(STREAM_MUSIC);          mp.setLooping(true);          mp.start();          try {              Thread.sleep(20*1000);          } catch (InterruptedException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }      }  }


ActivityInstrumentationTestCase2,SingleLaunchActivityTestCase,ActivityUnitTestCase主要来测试Activity相关API,方便之处是可以直接获取Activity

public class AdminMainTest extends ActivityInstrumentationTestCase2 {         private MainActivity mActivity;    private Instrumentation mInstrumentation;    private Button login;    private EditText account;    private EditText password;    private RadioGroup radioGroup;    //private RadioButton button;    private RadioButton button1;    private RadioButton button2;    private RadioButton button3;    private RadioButton button4;         private Context mContext;    private View buttonView;         public AdminMainTest(){        super(MainActivity.class); //目标Activity    }    @Before    protected void setUp() throws Exception {        super.setUp();        setActivityInitialTouchMode(false);        mInstrumentation=getInstrumentation();        mContext=mInstrumentation.getContext();        mActivity=getActivity();        login=(Button) mActivity.findViewById(com.example.example.R.id.landed);        account=(EditText) mActivity.findViewById(com.example.example.R.id.landed_account);        password=(EditText) mActivity.findViewById(com.example.example.R.id.landed_password);        radioGroup = (RadioGroup) mActivity.findViewById(R.id.landed_user_type);                button1=(RadioButton) mActivity.findViewById(R.id.landed_user_type_admin);        button2=(RadioButton) mActivity.findViewById(R.id.landed_user_type_publisher);        button3=(RadioButton)mActivity.findViewById(R.id.landed_user_type_common);        button4=(RadioButton)mActivity.findViewById(R.id.landed_user_type_visitor);    }     @After    protected void tearDown() throws Exception {        mActivity.finish();        super.tearDown();    }         public void testPreConditions(){        assertNotNull(mActivity);        assertNotNull(login);        assertNotNull(account);        assertNotNull(password);        assertNotNull(radioGroup);        assertNotNull(button1);        assertNotNull(button2);        assertNotNull(button3);        assertNotNull(button4);    }     public void input() {                  mActivity.runOnUiThread(new Runnable(){             @Override            public void run() {                // TODO Auto-generated method stub                SystemClock.sleep(1500);                account.requestFocus();                SystemClock.sleep(1500);                account.performClick();                //SystemClock.sleep(3000);            }        });        mInstrumentation.waitForIdleSync();                 sendKeys(KeyEvent.KEYCODE_S,KeyEvent.KEYCODE_O,                KeyEvent.KEYCODE_N,KeyEvent.KEYCODE_G);                 mActivity.runOnUiThread(new Runnable(){             @Override            public void run() {                // TODO Auto-generated method stub                SystemClock.sleep(1500);                password.requestFocus();                SystemClock.sleep(1500);                password.performClick();            }        });        mInstrumentation.waitForIdleSync();                 sendKeys(KeyEvent.KEYCODE_S,KeyEvent.KEYCODE_O,                KeyEvent.KEYCODE_N,KeyEvent.KEYCODE_G);                 mInstrumentation.waitForIdleSync();    }          public void testFirstRadioButton(){        assertTrue("The Admin button is checked",button1.isChecked());        //assertEquals("商品发布者",button.getText().toString());        assertEquals(R.id.landed_user_type_admin,radioGroup.getCheckedRadioButtonId());    }         public void testSecondRadioButton(){        //assertTrue("The Publisher button is checked",button2.isChecked());        //assertEquals(R.id.landed_user_type_publisher,radioGroup.getCheckedRadioButtonId());        assertEquals("商品发布者",button2.getText().toString());             }     public void testThirdRadioButton()    {        //assertTrue("The common user is checked",button3.isChecked());        //assertEquals(R.id.landed_user_type_common,radioGroup.getCheckedRadioButtonId());        assertEquals("普通用户",button3.getText().toString());    }            public void testFourthRadioButton()    {        //assertTrue("The guest is checked",button4.isChecked());        //assertEquals(R.id.landed_user_type_visitor,radioGroup.getCheckedRadioButtonId());        assertEquals("访客",button4.getText().toString());    }         public void testButton2Selection(){        testFirstRadioButton();        TouchUtils.clickView(this, button2);    //  assertFalse("The admin radio button should not be checked",button1.isChecked());        assertTrue("The publisher radio button should be checked",button2.isChecked());        assertEquals("The publisher button should be checked",R.id.landed_user_type_publisher,                radioGroup.getCheckedRadioButtonId());    }         public void testButton3Selection(){        testFirstRadioButton();        TouchUtils.clickView(this, button3);        assertTrue("The common user is checked",button3.isChecked());        assertEquals(R.id.landed_user_type_common,radioGroup.getCheckedRadioButtonId());    }         public void testButton4Selection(){        testFirstRadioButton();        TouchUtils.clickView(this, button4);        assertTrue("The guest is checked",button4.isChecked());        assertEquals(R.id.landed_user_type_visitor,radioGroup.getCheckedRadioButtonId());             }     /**     public void testRadioButtonChange(){        testFirstRadioButton();        TouchUtils.clickView(this, button);        assertFalse("The admin radio button should not be checked",button1.isChecked());        assertTrue("The publisher button should be checked",button.isChecked());        assertEquals("The publisher button should be checked",R.id.landed_user_type_publisher,                radioGroup.getCheckedRadioButtonId());    }**/    public void testInput(){        input();        assertEquals("song",account.getText().toString());        assertEquals("song",password.getText().toString());    }     @Test    public void testLogin(){        input();        //testRadioButtonChange();        mInstrumentation.runOnMainSync(new Runnable(){             @Override            public void run() {                // TODO Auto-generated method stub                SystemClock.sleep(1500);                login.requestFocus();                SystemClock.sleep(1500);                login.performClick();            }                     });    }      }

ServiceTestCase专门用来测试Service服务

public class MyServiceTest extends ServiceTestCase {    private String TAG="myservicetest";    private Context mContext;    /**     * 构造方法     */    public MyServiceTest() {        super(MyService.class);    }    /**     * 重写setUp方法,第一句调用super.setUp     */    protected void setUp() throws Exception {        super.setUp();        mContext = getContext();    }  // public void testAndroidTestCaseSetupProperly() {  // super.testAndroidTestCaseSetupProperly(); // }    protected void tearDown() throws Exception {        mContext = null;        super.tearDown();    }    /**     * 测试Service正确地启动     */    public void testStart() {        Log.i(TAG, "start testStart");            Intent intent = new Intent();            startService(intent);            MyService Serv=getService();            assertNotNull(Serv);        Log.i(TAG, "end testStart");        }    }    /**     * 测试Service正确的终止     */    public void teststop() {        Log.i(TAG, "start teststopService");            Intent intent = new Intent();            startService(intent);            MyService service = getService();            service.stopService(intent);         }}

 InstrumentationTestCase 相对于Activity,Service等测试,相对而言,比较灵活,其他测试很多都是继承自这个

public class TestHelloActiviry extends InstrumentationTestCase {            final String TAG = "TestHelloAppTestHelloApp";             Button mHelloTestButton;      EditText mHelloEditText;      HelloActivity mHelloTestActivity;      Instrumentation mInstrumentation;            public void testHelloActivity() {          Log.i(TAG, "call testHelloActivity()");          mHelloTestButton = (Button)mHelloTestActivity.findViewById(R.id.Button1);          mHelloEditText = (EditText)mHelloTestActivity.findViewById(R.id.EditText1);          for (int i = 0; i < 3; i++) {              //设置事件在主线程中执行              mInstrumentation.runOnMainSync(new Click(mHelloTestButton,mHelloEditText,Integer.toString(i)));              SystemClock.sleep(3000);          }                }            public void testHelloActivity2() {                }            private class Click implements Runnable{          Button button;          EditText editText;          String str;          Click(Button b,EditText e,String s){              button = b;              editText = e;              str = s;          }          @Override          public void run() {              editText.setText(str);                button.performClick();                        }      }            //负责testcase开始前的初始化工作      @Override      protected void setUp() throws Exception {          super.setUp();          Log.i(TAG, "call setUp()");          mInstrumentation = getInstrumentation();          Intent intent = new Intent();          intent.setClassName("com.example.hello", "com.example.hello.HelloActivity");          intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);          //通过intent触发activity          mHelloTestActivity = (HelloActivity)mInstrumentation.startActivitySync(intent);      }          @Override      protected void tearDown() throws Exception {          super.tearDown();                    Log.i(TAG, "tearDown()");      }              }


参考

Android自动化测试初探(二): Hierarchyviewer 捕获Element的实现原理


转载于:https://my.oschina.net/ososchina/blog/621740

更多相关文章

  1. 【阿里云镜像】切换阿里巴巴开源镜像站镜像——Debian镜像
  2. Android(安卓)Manifest.permission权限
  3. 初涉Android蓝牙开发
  4. Android通信之 Bluetooth
  5. Android通讯录数据库介绍与基本操作(增删改查)
  6. php与android的简单交互
  7. Android系统服务接口
  8. Android自动测试之benchmark test 简介
  9. android之高德地图学习

随机推荐

  1. android中读取assets中的文件
  2. 通过adb shell命令查看当前与用户交互的
  3. Android(安卓)布局学习
  4. android 比较靠谱的图片压缩
  5. android 判断当前application 是在前台还
  6. Android(安卓)各版本对应API以及相关特性
  7. android 启动时的短暂黑屏解决
  8. Android(安卓)仿抖音全屏 VideoView
  9. Android实现获取手机里面的所有图片
  10. android导入eclipse项目后,gradle版本引起