相关疑难解决方法(0)

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

我使用Android Studio 1.1.0的新单元测试支持功能运行了一些旧的测试.运行gradlew testDebug时,运行测试,但所有需要Context失败的测试都因为getContext(AndroidTestCase)/ getInstrumentation.getContext()(InstrumentationTestCase)都返回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);
    }  

}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

这是我的模块build.gradle:

apply plugin: …
Run Code Online (Sandbox Code Playgroud)

android unit-testing android-studio

22
推荐指数
3
解决办法
4万
查看次数

标签 统计

android ×1

android-studio ×1

unit-testing ×1