Android在非活动单元测试中的上下文

时间:2015-01-04 14:25:49

标签: android unit-testing junit android-volley android-instrumentation

我要测试我的单身OcRequestQueue.java课程,我希望Volley能够持续使用应用程序RequestQueue的生命周期。问题是它需要超出类范围的应用程序context,因为我想实现单独的表示和数据层,OcRequestQueue.java位于第二层。表示层尚未实现,所以我想对我所做的事情进行单元测试,所以我希望从context获得InstrumentationTestCase,但我得到的只是!! JUnit version 3.8 or later expected。如何对不扩展Activity的类进行单元测试?

com.data.OcRequestQueue.java

package com.data;
import android.content.Context;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;


/**
 * Created by mateusz on 03.01.15.
 */
public class OcRequestQueue {
    static RequestQueue requestQueue;
    static Context mContext;
    static Cache cache;
    static Network network;

    private static OcRequestQueue ourInstance = new OcRequestQueue();

    public static OcRequestQueue getInstance(Context context) {
        if (ourInstance == null) {
            mContext = context;
            requestQueue = getRequestQueue(mContext);
        }
        return ourInstance;
    }

    private static RequestQueue getRequestQueue(Context context) {
        cache = new DiskBasedCache(context.getCacheDir(), 1024 * 1024);
        network = new BasicNetwork(new HurlStack());
        return new RequestQueue(cache,network);
    }

    public OcRequestQueue() {

    }
}

com.data.test.OcRequestQueueTest.java

package com.data.test;

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

import com.data.OcRequestQueue;



public class OcRequestQueueTest extends InstrumentationTestCase {

    Context context;

    @Override
    public void setUp() throws Exception {
        context = getInstrumentation().getContext();
    }

    public void testGetInstance() throws Exception {
        assertEquals(new OcRequestQueue(), OcRequestQueue.getInstance(context));
    }
}

bulid.gardle

apply plugin: 'com.android.library'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
repositories {
    mavenCentral()
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile 'junit:junit:4.+'
    compile 'com.google.inject:guice:4.0-beta5'
    def domainLayer = project(':domain')
    //project dependencies
    compile domainLayer
}

0 个答案:

没有答案