在Android Studio的单元测试功能中获取AndroidTestCase或InstrumentationTestCase中的上下文

前端之家收集整理的这篇文章主要介绍了在Android Studio的单元测试功能中获取AndroidTestCase或InstrumentationTestCase中的上下文前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些旧的测试运行 Android Studio 1.1.0的新的单元测试支持功能.
当运行gradlew testDebug时,运行测试,但是由于getContext(AndroidTestCase)/ getInstrumentation.getContext()(InstrumentationTestCase))都返回null,所以需要Context的所有测试都会返回null.

我该如何解决

以下是我尝试过的两种变体:

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之前都运行,并运行在设备/模拟器上.

编辑:

Heres 2截图失败的InstrumentationTestCase和AndroidTestCase:

解决方法

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

较新的例子:

我得到这些工作,而不部署到设备.将测试放在/ src / main / test /文件夹中.

这是一个较新的例子,我把你的例子和我们自己的临时测试项目测试了.我通过命令行运行测试:./gradlew clean test.请在这里阅读更多: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);
    }
}

谷歌老例子:

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

使用InstrumentationTestCase:

测试资源:

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

使用ActivityTestCase:

测试资源:

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

使用AndroidTestCase:

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

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的源代码,您需要自己设置一个上下文:

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

原文链接:https://www.f2er.com/android/312487.html

猜你在找的Android相关文章