在 Android Studio 的单元测试功能中获取 AndroidTestCase 或 InstrumentationTestCase 中的上下文 [英] Getting context in AndroidTestCase or InstrumentationTestCase in Android Studio's Unit Test feature

查看:35
本文介绍了在 Android Studio 的单元测试功能中获取 AndroidTestCase 或 InstrumentationTestCase 中的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Android Studio 1.1.0 的新单元测试支持功能运行了一些旧测试.运行 gradlew testDebug 时,测试会运行,但所有需要 Context 的测试都失败了,因为 getContext (AndroidTestCase)/getInstrumentation.getContext() (InstrumentationTestCase) 都返回 null.

I got some of my old tests running with Android Studio 1.1.0's new unit test support feature. When running gradlew testDebug the tests are run, but all of the tests that require a Context fail because getContext (AndroidTestCase) / getInstrumentation.getContext() (InstrumentationTestCase) both return null.

我该如何解决这个问题?

How can I solve this?

这是我尝试过的两种变体:

Here's two variants I've tried:

import android.content.Context;
import android.test.InstrumentationTestCase;

public class TestTest extends InstrumentationTestCase {

    Context context;

    public void setUp() throws Exception {
        super.setUp();

        context = getInstrumentation().getContext();

        assertNotNull(context);

    }

    public void testSomething() {

        assertEquals(false, true);
    }  

}

import android.content.Context;
import android.test.AndroidTestCase;

public class TestTest extends AndroidTestCase {

    Context context;

    public void setUp() throws Exception {
        super.setUp();

        context = getContext();

        assertNotNull(context);

    }

    public void testSomething() {

        assertEquals(false, true);
    }

}

这是我模块的build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.0"

    testOptions {
        unitTests.returnDefaultValues = true
    }

    defaultConfig {
        applicationId "com.example.test.penistest"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    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'
    testCompile 'junit:junit:4.12'
}

这里是项目的build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

在升级到 AS 1.1.0 并在设备/模拟器上运行之前,我的所有测试都有效.

My tests all worked before upgrading to AS 1.1.0 and ran on a device / emulator.

以下是 InstrumentationTestCase 和 AndroidTestCase 失败的 2 个屏幕截图:

Heres 2 screenshots of failing InstrumentationTestCase and AndroidTestCase:

推荐答案

更新 - 请使用 Espresso 编写仪器测试

较新的示例:

我让这些工作无需部署到设备.将 测试放在 /src/main/test/ 文件夹中.

Updated - Please use Espresso for writing instrumentation tests

Newer Examples:

I got these working without deploying to a device. Put the tests in the /src/main/test/ folder.

这是较新的示例,我采用了您的示例并在我自己的临时测试项目中对其进行了测试.我通过命令行运行测试:./gradlew clean test.请在此处阅读更多信息:https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support.

Here are newer examples, I took your examples and tested them in my own temporary test project. I ran the tests via command line: ./gradlew clean test. Please read more here: https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support.

顶部 build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.1.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

应用build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.0"

    defaultConfig {
        applicationId "com.test"
        minSdkVersion 9
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    testOptions { // <-- You need this
        unitTests {
            returnDefaultValues = true
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.0.0'

    testCompile 'junit:junit:4.12' // <-- You need this
}

基本测试:

InstrumentationTestCaseTest 用于测试 ContextAssertions.

import android.content.Context;
import android.test.InstrumentationTestCase;
import android.test.mock.MockContext;

public class InstrumentationTestCaseTest extends InstrumentationTestCase {

    Context context;

    public void setUp() throws Exception {
        super.setUp();

        context = new MockContext();

        assertNotNull(context);

    }

    public void testSomething() {

        assertEquals(false, true);
    }

}

ActivityTestCase 来测试你的 Resources.

import android.content.Context;
import android.content.res.Resources;
import android.test.ActivityTestCase;

public class ActivityTestCaseTest extends ActivityTestCase {

    public void testFoo() {

        Context testContext = getInstrumentation().getContext();
        Resources testRes = testContext.getResources();

        assertNotNull(testRes);
        assertNotNull(testRes.getString(R.string.app_name));
    }
}

AndroidTestCase 来测试 ContextAssertions.

import android.content.Context;
import android.test.AndroidTestCase;
import android.test.mock.MockContext;

public class AndroidTestCaseTest extends AndroidTestCase {

    Context context;

    public void setUp() throws Exception {
        super.setUp();

        context = new MockContext();

        setContext(context);

        assertNotNull(context);

    }

    // Fake failed test
    public void testSomething()  {
        assertEquals(false, true);
    }
}

谷歌搜索旧示例:

在谷歌搜索了很多关于这个错误之后,我相信你的赌注是使用 getInstrumentation().getContext().getResources().openRawResource(R.raw.your_res). 或类似的东西以测试您的资源.

Googling Old Examples:

After Googling a lot bout this error, I believe your bet is to use getInstrumentation().getContext().getResources().openRawResource(R.raw.your_res). or something similar in order to test your resources.

测试资源:

public class PrintoutPullParserTest extends InstrumentationTestCase {

    public void testParsing() throws Exception {
        PrintoutPullParser parser = new PrintoutPullParser();
        parser.parse(getInstrumentation().getContext().getResources().getXml(R.xml.printer_configuration));
    }
}

来源:https://stackoverflow.com/a/8870318/950427https://stackoverflow.com/a/16763196/950427

测试资源:

public class Test extends ActivityTestCase {

   public void testFoo() {  

      // .. test project environment
      Context testContext = getInstrumentation().getContext();
      Resources testRes = testContext.getResources();
      InputStream ts = testRes.openRawResource(R.raw.your_res);

      assertNotNull(testRes);
   }    
}

来源:https://stackoverflow.com/a/9820390/950427

获取Context(一个简单的技巧):

Getting the Context (a simple hack):

private Context getTestContext() {
    try {
        Method getTestContext = ServiceTestCase.class.getMethod("getTestContext");
        return (Context) getTestContext.invoke(this);
    } catch (final Exception exception) {
        exception.printStackTrace();
        return null;
    }
}

来源:https://stackoverflow.com/a/14232913/950427

但是,如果您查看AndroidTestCase 的源代码,看起来您需要自己设置一个Context:

But, if you look a the source code of AndroidTestCase, it looks like you need to set a Context yourself:

来源:http://alvinalexander.com/java/jwarehouse/android/core/java/android/test/AndroidTestCase.java.shtml

这篇关于在 Android Studio 的单元测试功能中获取 AndroidTestCase 或 InstrumentationTestCase 中的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆