1.Android unit testing

  • JUnit4 rule for AndroidX Test
  • You can check the official document, how to write Test.

2. Why is the context fetched by AndroidTest empty

2.1 Context is available but empty

// To get the context
Context context = ApplicationProvider.getApplicationContext();
Copy the code

2.2 ApplicationProvider source

  • View the source code, like the Internet, InstrumentationRegistry getInstrumentation () getTargetContext ().
/**
 * Provides ability to retrieve the current application {@link Context} in tests.
 *
 * <p>This can be useful if you need to access the application assets (eg
 * <i>getApplicationContext().getAssets()</i>), preferences (eg
 * <i>getApplicationContext().getSharedPreferences()</i>), file system (eg
 * <i>getApplicationContext().getDir()</i>) or one of the many other context APIs in test.
 */
public final class ApplicationProvider {

  private ApplicationProvider(a) {}

  /**
   * Returns the application {@link Context} for the application under test.
   *
   * @see {@link Context#getApplicationContext()}
   */
  @SuppressWarnings("unchecked")
  public static <T extends Context> T getApplicationContext(a) {
    return(T) InstrumentationRegistry.getInstrumentation().getTargetContext().getApplicationContext(); }}Copy the code

2.3 Instrumentation source

  • We look at the source of the Instrumentation, found that his mAppContext is not initialized, fetch of course is empty.
public class Instrumentation {.../*package*/ final void init(ActivityThread thread, Context instrContext, Context appContext, ComponentName component, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection) {
        mThread = thread;
        mMessageQueue = mThread.getLooper().myQueue();
        mInstrContext = instrContext;
        mAppContext = appContext;
        mComponent = component;
        mWatcher = watcher;
        mUiAutomationConnection = uiAutomationConnection;
    }

	// Return mAppContext directly
    public Context getTargetContext(a) {
        returnmAppContext; }... }Copy the code

3. Correct acquisition method

3.1 Viewing documents on the official website

  • Check out the AndroidJUnitRunner documentation.
  • To obtain the context, you need to create a custom subclass of Application.

3.2 create application

  • Create the Application in the AndroidTest directory.

public class TestApplication extends Application {
	private Context mContext;
	
    @Override
    public void onCreate(a) {
        super.onCreate();
        mContext = getApplicationContext();
    }
    
     public static Context getContext(a) {
        returnmContext; }}Copy the code
  • At this point the fetch is not empty.
@RunWith(AndroidJUnit4.class)
public class MyTest   {
    @Test
    public void test(a) {
        Context context = ApplicationProvider.getApplicationContext();
        / / can also
        //TestCaseApplication.getContext();}}Copy the code