我在擴展ActivityInstrumentationTestCase2的Android中運行junit測試。我正在使用它來啓動一項活動。Android:如何在使用ActivityInstrumentationTestCase2進行測試時獲取上下文?
該活動使用應用程序對象的子類來獲取一些參數。我從上下文中獲取應用程序對象。
不幸的是,ActivityInstrumentationTestCase2不提供對上下文的訪問。有沒有辦法在之前訪問上下文?
我在擴展ActivityInstrumentationTestCase2的Android中運行junit測試。我正在使用它來啓動一項活動。Android:如何在使用ActivityInstrumentationTestCase2進行測試時獲取上下文?
該活動使用應用程序對象的子類來獲取一些參數。我從上下文中獲取應用程序對象。
不幸的是,ActivityInstrumentationTestCase2不提供對上下文的訪問。有沒有辦法在之前訪問上下文?
爲了能夠使用setApplication()注入應用程序,您應該使用ActivityUnitTestCase,因爲它僅在此測試用例類中可用。
默認情況下,ActivityUnitTestCase創建一個隱藏的MockApplication對象,該對象用作被測試的應用程序。
你可以從儀表對象的應用程序上下文:使用
AndroidTestCase
和需要的應用程序子類
getInstrumentation().getTargetContext().getApplicationContext()
嗚呼!神奇的答案。 – 2014-11-11 23:19:23
謝謝你的工作 – 2016-09-28 11:52:01
對於那些:
MyApplication context = (MyApplication) getContext().getApplicationContext();
謝謝 - 有沒有我可以使用ActivityUnitTestCase啓動一個活動嗎? – 2011-05-15 22:22:30
startActivity [http://developer.android.com/reference/android/app/Activity.html#startActivity(android.content.Intent)] – 2011-05-15 22:23:56
ActivityUnitTestCase ist棄用自API級別24 [link](https:// developer。 android.com/reference/android/test/ActivityUnitTestCase.html) – maryBlaa 2016-12-01 11:04:41