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

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

问题描述

我得到了我的一些与Android工作室1.1.0新的单元测试支持功能运行旧的测试。 当运行gradlew testDebug测试运行,但都需要一个背景下的测试失败,因为的getContext (AndroidTestCase)/ getInstrumentation.getContext()(InstrumentationTestCase)都返回空值。

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.

编辑:

2的继承人截图失败InstrumentationTestCase和AndroidTestCase的:

Heres 2 screenshots of failing InstrumentationTestCase and AndroidTestCase:

推荐答案

我得到这些的工作没有部署到设备。将在测试中的 / src目录/主/测试/ 文件夹。

Updated - Newer Examples:

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

下面是较新的例子,我把你的例子,在我自己的临时测试项目测试它们。我跑的测试通过命令行: ./ gradlew干净的测试。请在这里阅读更多:<一href="https://sites.google.com/a/android.com/tools/tech-docs/unit-testing-support">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 测试上下文断言

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 来测试你的资源

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 测试上下文断言

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));
    }
}

来源: http://stackoverflow.com/a/8870318/950427 和的http://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);
   }    
}

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

获取上下文(一个简单的黑客):

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;
    }
}

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

不过,如果你看一个源$ C ​​$ AndroidTestCase 的C,它看起来像你需要设置一个上下文自己:

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

来源:<一href="http://alvinalexander.com/java/jwarehouse/android/core/java/android/test/AndroidTestCase.java.shtml">http://alvinalexander.com/java/jwarehouse/android/core/java/android/test/AndroidTestCase.java.shtml

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

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