ApplicationTestCase deprecated in API level 24

后端 未结 2 1626
一生所求
一生所求 2021-02-06 23:32

I created a default empty project on Android Studio 2.1.2 with API 24. In the sample project, Google offers a depreciated class Applica

相关标签:
2条回答
  • 2021-02-06 23:50

    The new androidTest example that the beta version of Android Studio 2.2 generates, look like this:

    @RunWith(AndroidJUnit4.class)
    public class ExampleInstrumentedTest {
        @Test
        public void useAppContext() throws Exception {
            // Context of the app under test.
            Context appContext = InstrumentationRegistry.getTargetContext();
    
            assertEquals("org.mypackage", appContext.getPackageName());
        }
    }
    

    Just like the deprecation warning suggests, the new instrumentation tests should use InstrumentationRegistry instead of extending from AndroidTestCase. Run them with AndroidJUnit4.

    The relevant dependencies section in build.gradle looks like this:

    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    
    0 讨论(0)
  • 2021-02-06 23:57

    As indicated in the API documentation the API has been deprecated and instead use of the InstrumentationRegistry.getTargetContext() will in turn call onCreate method of your Application class.

    The getTargetContext will call the ApplicationStartupService class defined in Android Manifest as below.

        <?xml version="1.0" encoding="utf-8"?>
         <manifest xmlns:android="http://schemas.android.com/apk/res/android"
           <application
               android:name=".service.ApplicationStartupService"
    
     public class ApplicationStartupService extends Application
     {
    
           /**
             * Method initializes the application configuration
           */
           @Override
           public void onCreate(){
    
              super.onCreate();
    
              this.initResources()
           }
    
          private void initResource(){
              //do your application init work here.
          }
    }
    
    Test Class
    
      @RunWith(AndroidJUnit4.class)      
      public class ApplicationStartupServiceTest {
    
      @Test
      public void testResourcesAreInitializedd() throws Exception {
       //do your assertions here.
      }
    

    https://developer.android.com/reference/android/test/ApplicationTestCase

    0 讨论(0)
提交回复
热议问题