AndroidStudio通过UIAutomator进行测试 用例编写(二)

样本格式:

/**

* 样例

*/

@RunWith(AndroidJUnit4.class)

@SdkSuppress(minSdkVersion = 18)

public class BasicSampleTest {

    private final static String TAG = "BasicSampleTest";

    private UiDevice mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

    private static final String FLAG = "";//选取主activity的 flag //TODO

    private static final String TEST_PACKAGE_NAME = "";//app package Name //TODO

    private static final int LAUNCH_TIMEOUT = 2000;

    private int[] controlInfo = new int[10]; //{x, y, centerX, centerY, width, height};//控件坐标信息

    private static final int SCRE_WIDTH = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).getInstance().getDisplayWidth();//获取屏幕宽度

    private static final int SCRE_HEIGHT = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).getInstance().getDisplayHeight();//获取屏幕高度

    /*************************************定义ID begin**********************************************************/

    //private static final String SAMP = "samp";

    /*************************************定义ID end**********************************************************/

    /*************************************Test Before begin**********************************************************/

    /**

    * 从主屏幕启动应用

    */

    @Before

    public void startMainActivityFromHomeScreen() {

        // wakeup screen

        try {

            if (!mDevice.isScreenOn()) {

                mDevice.wakeUp();

            }

        } catch (RemoteException e) {

            Log.e(TAG, "Device wakeUp exception!");

            e.printStackTrace();

        }

        // Wait for launcher

        final String launcherPackage = getLauncherPackageName();

        assertThat(launcherPackage, notNullValue());

        mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);

        //如果测试应用的主 activity 未显示 则开启

        if (mDevice.wait(Until.hasObject(By.pkg(TEST_PACKAGE_NAME).depth(0)), LAUNCH_TIMEOUT)) {

            //如果应用已经启动,判断是否是在 main activity 不在重新启动

            Log.e(TAG, "应用已经启动");

            UiObject mainActivityFlag = mDevice.findObject(new UiSelector().resourceId(FLAG));//获取主activity的FLAG

            if (!mainActivityFlag.exists()) {//根据 main activity 的元素是否存在判断是否重新启动

                Log.e(TAG, "重新启动app");

                startApp(TEST_PACKAGE_NAME, LAUNCH_TIMEOUT);

            }

        } else {

            Log.e(TAG, "应用未启动,启动应用");

            startApp(TEST_PACKAGE_NAME, LAUNCH_TIMEOUT);

        }

    }

    /**

    * Uses package manager to find the package name of the device launcher. Usually this package

    * is "com.android.launcher" but can be different at times. This is a generic solution which

    * works on all platforms.`

    */

    public String getLauncherPackageName() {

        // Create launcher Intent

        final Intent intent = new Intent(Intent.ACTION_MAIN);

        intent.addCategory(Intent.CATEGORY_HOME);

        // Use PackageManager to get the launcher package name

        PackageManager pm = InstrumentationRegistry.getContext().getPackageManager();

        ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);

        return resolveInfo.activityInfo.packageName;

    }

    /**

    * 进入抽屉点击启动APP

    *

    * @param className

    * @param dex

    * @param appName

    */

    public void clickApp(String className, int dex, String appName) {

        try {

            UiObject appItem = mDevice.findObject(new UiSelector().className(className).index(dex).childSelector(new UiSelector().text(appName)));

            appItem.click();

        } catch (UiObjectNotFoundException e) {

            e.printStackTrace();

        }

    }

    /**

    * 打开app

    *

    * @param packageName

    * @param timeOut

    */

    public void startApp(String packageName, int timeOut) {

        Context context = InstrumentationRegistry.getContext();

        final Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);    // Clear out any previous instances

        context.startActivity(intent);

        // Wait for the app to appear

        mDevice.wait(Until.hasObject(By.pkg(packageName).depth(0)), timeOut);

    }

    /**

    * 获取控件坐标信息

    * @param resourceID

    * @return

    */

    public int[] getControlInfo(String resourceID) {//TODO

        UiObject2 control = mDevice.findObject(By.res(TEST_PACKAGE_NAME, resourceID));

        Log.d(TAG, "control====" + control);

        Rect controlRect = control.getVisibleBounds();

        Log.d(TAG, "controlRect====" +controlRect);

        controlInfo[0] = controlRect.right;

        controlInfo[1] = controlRect.bottom;

        controlInfo[2] = controlRect.centerX();

        controlInfo[3] = controlRect.centerY();

        controlInfo[4] = controlRect.width();

        controlInfo[5] = controlRect.height();

        return controlInfo;

    }

    /**

    * 点击控件

    * @param stringId

    * @param isLongClick

    */

    private void clickControl(String stringId, boolean isLongClick) {

        Log.d(TAG, "clickControl-stringId=====" + stringId);

        if (stringId != null) {

            if (isLongClick) {

                mDevice.findObject(By.res(TEST_PACKAGE_NAME, stringId)).longClick();

            } else {

                mDevice.findObject(By.res(TEST_PACKAGE_NAME, stringId)).click();

            }

        }

    }

    /**

    * 获取控件 TEXT 内容

    * @param stringId

    * @return

    */

    private String getControlText(String stringId) {

        Log.d(TAG, "getControlText-stringId=====" + stringId);

        String text = mDevice.findObject(By.res(TEST_PACKAGE_NAME, stringId)).getText().trim();

        if (text != null) {

            return text;

        } else {

            return "TEST_ERROR";

        }

    }

    /*****************************************Test Before end**************************************************/

    /*****************************************定义其他方法 begin**************************************************/

    /**

    * 获取屏幕宽度

    * @param activity

    * @return

    */

    public final static int getWindowsWidth(Activity activity) {

        DisplayMetrics displayMetrics = new DisplayMetrics();

        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        return displayMetrics.widthPixels;

    }

    /**

    * 获取屏幕高度

    * @param activity

    * @return

    */

    public final static int getWindowsHight(Activity activity) {

        DisplayMetrics displayMetrics = new DisplayMetrics();

        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        return displayMetrics.heightPixels;

    }

    /**

    * 获取控件高度

    * @param view

    * @return

    */

    public final static int getViewhight(View view) {

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

        view.measure(w, h);

        int height = view.getMeasuredHeight();

        return height;

    }

    /**

    * 获取控件宽度

    * @param view

    * @return

    */

    public final static int getViewWidth(View view) {

        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);

        view.measure(w, h);

        int width = view.getMeasuredWidth();

        return width;

    }

    /*****************************************定义其他方法 begin**************************************************/

    /***************************************测试 CASE  begin**************************************************/

    /**

    *

    */

    @Test

    public void test_basic_sample_001() throws InterruptedException {

        sleep(500);

        assertEquals("message", "expected_result", "actual_result");

    }

你可能感兴趣的:(AndroidStudio通过UIAutomator进行测试 用例编写(二))