Ui Android Studio 中的 Automator 2.0 项目

Ui Automator 2.0 project in Android Studio

我想在 Android Studio 中设置一个项目。 但是,我不需要Android应用程序,只需要测试项目。

根据最新的 release of UiAutomator,我试图设置一个 class 扩展 ActivityInstrumentationTestCase2 并从那里开始我的测试。

但是,我遇到了一件事:我不知道如何在不将项目制作为应用程序的情况下创建项目。

创建新项目的选项是:

我做到了:

  1. 开始一个新项目,给它起个名字,设置minSDK然后选择"No activity"
  2. 打开build.gradle(app下),添加Testing Support Library
  3. 末尾提到的依赖和检测信息
  4. 打开src下的androidTest,修改主文件:修改为ActivityInstrumentationTestCase2,添加setUp和tearDown;定义了 RunWith Junit4(如 Testing Support Library 中所示)
  5. 我构建项目(构建成功)- 在 "action bar"
  6. 中按旁边的绿色箭头进行构建

我的问题是:

我很感激安装和 运行 说明将同时说明如何通过 Android Studio 和使用命令行(如果您只知道其中之一 post 无论如何请)。

注意:这是我第一次使用 Android Studio

提前致谢。

编辑:

现在我可以构建 运行 但它告诉我我没有测试 运行(空测试套件)。这是我的 graddle 和我的代码。

我的build.graddle如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "androidexp.com.ceninhas"
        minSdkVersion 21
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
      testInstrumentationRunner="android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'LICENSE.txt'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0'
}

我的源代码(在src/androidTest/java/package下)是:

@RunWith(AndroidJUnit4.class)
public class ApplicationTest extends ActivityInstrumentationTestCase2<Activity> {
    public final static String ACTIVITY_NAME = "com.calculator.Main";
    public final static Class<?> autActivityClass;

    static {
        try {
            autActivityClass = Class.forName(ACTIVITY_NAME);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public ApplicationTest(){
        super((Class<Activity>)autActivityClass);
    }

    @Before
    public void setUp() throws Exception{
        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
    }

    @After
    public void tearDown() throws Exception{
        super.tearDown();
    }

    @Test
    public void cenas(){
        assertTrue(true);
    }
}

控制台上的 运行 日志是:

Testing started at 18:06 ...
Waiting for device.
Target device: lge-nexus_5-08e506c10ddef123
Uploading file
    local path: C:\Users\Ines\workspace\Ceninhas\app\build\outputs\apk\app-debug.apk
    remote path: /data/local/tmp/androidexp.com.ceninhas
No apk changes detected. Skipping file upload, force stopping package instead.
DEVICE SHELL COMMAND: am force-stop androidexp.com.ceninhas
Uploading file
    local path: C:\Users\Ines\workspace\Ceninhas\app\build\outputs\apk\app-debug-androidTest-unaligned.apk
    remote path: /data/local/tmp/androidexp.com.ceninhas.test
No apk changes detected. Skipping file upload, force stopping package instead.
DEVICE SHELL COMMAND: am force-stop androidexp.com.ceninhas.test
Running tests
Test running startedFinish
Empty test suite.

我做错了什么?

我也在使用 AndroidStudio 的 uiautomator 2.0。以下是您问题的一些答案。

How do I install this in the device? How do I run it in the device?

确保您的设备已使用

连接
adb devices

如果没有,您必须使用

连接它
adb kill-server
adb connect xxx.xxx.xxx.xxx

然后在 AndroidStudio 中,右键单击您的测试 class,然后单击 "Run YourTestCase"。

Do I need to do anything in the AndroidManifest?

我的清单中没有什么特别的,但请务必添加

android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}

在你的 build.gradle

Am I editing in the right place? Should I do anything under src/main?

是的,您在正确的地方进行编辑。但是您可以将您的代码移动到 src/main。为此,您需要在 build.gradle 文件中将 androidTestCompile 更改为 compile

我还没有尝试 运行 从命令行进行测试,但您可以查看 AndroidStudio 命令,也许它可以提供帮助。

希望对你有所帮助。

编辑 1

我用这个代码

build.gradle (projectRoot)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.0"

    lintOptions {
        abortOnError false
    }
    packagingOptions {
        exclude 'NOTICE'
        exclude 'LICENSE.txt'
    }
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'
    compile 'com.android.support.test:testing-support-lib:0.1'
    compile 'com.android.support.test.uiautomator:uiautomator-v18:2.0.0'
    compile project(':aiccore')
}

LoginTestCase (projectRoot/src/main/LoginTestCase.java)

public class LoginTestCase extends InstrumentationTestCase {

    protected UiDevice device = null;
    protected String appName;

    public LoginTestCase() {
        this("YourAppName")
    }

    public LoginTestCase(String appName) {
        this.appName = appName;
    }

    public void runApp(String appName) throws UiObjectNotFoundException, RemoteException {
        device = UiDevice.getInstance(getInstrumentation());
        device.pressHome();
        device.waitForWindowUpdate("", 2000);

        UiObject2 allAppsButton = device.findObject(By.desc("Apps"));
        allAppsButton.click();
        device.waitForWindowUpdate("", 2000);

        UiScrollable appViews = new UiScrollable(new UiSelector().scrollable(true));
        appViews.setAsHorizontalList();

        UiObject settingsApp = appViews.getChildByText(new UiSelector().className(TextView.class.getName()), appName);
        settingsApp.clickAndWaitForNewWindow();

        assertTrue("Unable to detect app", settingsApp != null);
    }

    @Override
    public void setUp() throws RemoteException, UiObjectNotFoundException {
        this.runApp(appName);
    }

    @Override
    public void tearDown() throws RemoteException, UiObjectNotFoundException {
        //Empty for the moment
    }

    public void testUS1() {
        UiObject2 usernameLabel = device.findObject(By.clazz(TextView.class.getName()).text("Username"));
        assertTrue("Username label not found", usernameLabel != null);
    }

嗯,实际上,你不应该那样写测试代码。把你的代码放在src/androidTest文件夹下,然后像这样写测试代码:

@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class ChangeTextBehaviorTest {

    private static final String BASIC_SAMPLE_PACKAGE
            = "com.example.android.testing.uiautomator.BasicSample";
    private static final int LAUNCH_TIMEOUT = 5000;
    private static final String STRING_TO_BE_TYPED = "UiAutomator";
    private UiDevice mDevice;

    @Before
    public void startMainActivityFromHomeScreen() {
        // Initialize UiDevice instance
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        // Start from the home screen
        mDevice.pressHome();

        // Wait for launcher
        final String launcherPackage = mDevice.getLauncherPackageName();
        assertThat(launcherPackage, notNullValue());
        mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
                LAUNCH_TIMEOUT);

        // Launch the app
        Context context = InstrumentationRegistry.getContext();
        final Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
        // Clear out any previous instances
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

        // Wait for the app to appear
        mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
                LAUNCH_TIMEOUT);
    }
    @Test
    public void checkPreconditions() {
        assertThat(mDevice, notNullValue());
    }

    @Test
    public void testChangeText_sameActivity() {
        // Type text and then press the button.
        mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "editTextUserInput"))
                .setText(STRING_TO_BE_TYPED);
        mDevice.findObject(By.res(BASIC_SAMPLE_PACKAGE, "changeTextBt"))
                .click();

        // Verify the test is displayed in the Ui
        UiObject2 changedText = mDevice
                .wait(Until.findObject(By.res(BASIC_SAMPLE_PACKAGE, "textToBeChanged")),
                        500 /* wait 500ms */);
        assertThat(changedText.getText(), is(equalTo(STRING_TO_BE_TYPED)));
    }
}

详情请看:UIAutomator Test sample