我有一個ActivityInstrumentationTestCase2,並且我沒有獲得測試上下文的運氣。Android ActivityInstrumentationTestCase2獲取上下文的NullPointerException
package com.vsnetworks.vsnmedia.test;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
import com.vsnetworks.vsnmedia.MainActivity;
import com.vsnetworks.vsnmedia.VSWebViewClient;
public class TestMimeTypes extends ActivityInstrumentationTestCase2<MainActivity> {
Activity activity;
Context context;
public TestMimeTypes() {
super(MainActivity.class);
}
public void setUp() throws Exception {
super.setUp();
activity = getActivity();
context = activity.getApplicationContext();
}
public void test() {
String external = context.getExternalFilesDir(null).toString();
}
這是我得到的錯誤:
[exec] com.vsnetworks.vsnmedia.test.TestMimeTypes:INSTRUMENTATION_RESULT: shortMsg=java.lang.NullPointerException
[exec] INSTRUMENTATION_RESULT: longMsg=java.lang.NullPointerException: Unable to start activity ComponentInfo{com.vsnetworks.vsnmedia/com.vsnetworks.vsnmedia.MainActivity}: java.lang.NullPointerException
[exec] INSTRUMENTATION_CODE: 0
我認爲它的上下文相關的,因爲如果我這樣做了如下:
Context context = this.getInstrumentation().getTargetContext();
我得到(第37行是context.getExternal線)
[exec] com.vsnetworks.vsnmedia.test.TestMimeTypes:
[exec] Error in test:
[exec] java.lang.NullPointerException
[exec] at com.vsnetworks.vsnmedia.test.TestMimeTypes.test(TestMimeTypes.java:37)
[exec] at java.lang.reflect.Method.invokeNative(Native Method)
[exec] at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
[exec] at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
[exec] at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:192)
[exec] at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
[exec] at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
[exec] at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
[exec] at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1584)
[exec]
[exec] Test results for InstrumentationTestRunner=..E
[exec] Time: 0.292
[exec]
[exec] FAILURES!!!
[exec] Tests run: 2, Failures: 0, Errors: 1
我也嘗試過所有下面有相同的錯誤,甚至在幾個地方也有getInstrumentation.waitForIdleSync()(我在另一個線程中看到)。我試着創建新的MainActivity()對象,並從那裏獲取上下文以及getActivity(),同樣的問題。
context = getInstrumentation().getContext();
context = getInstrumentation().getTargetContext();
context = activity.getApplicationContext();
context = activity.getBaseContext();
那麼我在做什麼錯了?
編輯1 - 它會出現此問題只發生在模擬器上。如果我使用真實設備來運行測試,它們都會通過。
您需要使用'getInstrumentation()。getTargetedContext()'! – 2015-05-19 07:53:21