Android Studio中的Ui Automator 2.0项目

时间:2015-03-24 16:35:43

标签: android android-studio uiautomator android-uiautomator android-instrumentation

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

在最新的release of UiAutomator之后,我试图设置一个扩展ActivityInstrumentationTestCase2的类并从那里开始我的测试。

然而,我偶然发现了一件事:我无法弄清楚如何创建项目而不会将其变成应用程序。

创建新项目的选项包括:

  • 启动新的Android Studio项目
  • 打开现有项目
  • 导入项目

我做了:

  1. 开始一个新项目,给它一个名字,设置minSDK并选择"没有活动"
  2. 打开build.gradle(在app下)并添加Testing Support Library
  3. 末尾提到的依赖项和工具信息
  4. 在src下打开androidTest并更改主文件:更改为ActivityInstrumentationTestCase2,添加setUp和tearDown;定义了RunWith Junit4(如Testing Support Library所示)
  5. 我构建项目(构建成功) - 按下"操作栏旁边的绿色箭头"
  6. 我的问题是:

    • 如何在设备中安装?
    • 如何在设备中运行它?
    • 我是否需要在AndroidManifest中做任何事情?
    • 我在正确的地方编辑吗?我应该在src / main下做什么吗?

    我很欣赏安装和运行说明适用于如何通过Android Studio和使用命令行(如果您只知道其中一个请发布它)。

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

    提前致谢。

    修改

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

    我的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.
    

    我做错了什么?

2 个答案:

答案 0 :(得分:1)

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

  

如何在设备中安装?   如何在设备中运行它?

确保使用

连接设备
adb devices

如果没有,则必须使用

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

然后从AndroidStudio,右键单击您的测试类,然后单击“运行YourTestCase”。

  

我是否需要在AndroidManifest中做任何事情?

我的清单中没有任何特别之处,但请务必添加

android {
    defaultConfig {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}
你的build.gradle中的

  

我在正确的地方编辑吗?我应该在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);
    }

答案 1 :(得分:0)

嗯,实际上,你不应该这样编写测试代码。只需将代码保存在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