Android應用開發時,邏輯接口使用單元測試,比較方便驗證接口的正確性。有些接口需要context對象,可能依賴的包中使用了getApplicationContext,因此在傳入context時,一般傳入ApplicationContext,依賴包中也就不會出錯了。
單元測試中獲取context方法如下:
// 非ApplicationContext,依賴包可能會出錯
mContext = InstrumentationRegistry.getContext();
// ApplicationContext
mContext = InstrumentationRegistry.getTargetContext();