AndroidJUnit4.class is deprecated: How to use androidx.test.ext.junit.runners.AndroidJUnit4?

前端 未结 8 1648
傲寒
傲寒 2020-12-04 08:04

For my instrumentation tests I was using

@RunWith(AndroidJUnit4.class)

from

import androidx.test.runner.AndroidJUnit4;
         


        
8条回答
  •  执笔经年
    2020-12-04 08:31

    For me the following steps worked:
    1. Replace the androidx libraries with the one posted here . my final app/build.gradle looked like this:

    android {
        ...
        defaultConfig {
            ...
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    
        }
        ...
    }
    
    dependencies {
        ...
        testImplementation 'junit:junit:4.12'
    
        // Core library
        androidTestImplementation 'androidx.test:core:1.2.0'
    
        // AndroidJUnitRunner and JUnit Rules
        androidTestImplementation 'androidx.test:runner:1.2.0'
        androidTestImplementation 'androidx.test:rules:1.2.0'
    
        // Assertions
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.ext:truth:1.2.0'
        androidTestImplementation 'com.google.truth:truth:0.42'
    
        // Espresso dependencies
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    
    }
    

    I then manually replaced the imported modules in my ExampleInstrumentTest.java class with latest classes:

    import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner;
    import androidx.test.platform.app.InstrumentationRegistry;
    import androidx.test.rule.ActivityTestRule;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Rule;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    
    @RunWith(AndroidJUnit4ClassRunner.class)
    public class ExampleInstrumentedTest {
        ...
        @Rule
        public final ActivityTestRule main = new ActivityTestRule<>(MainActivity.class, true);
    
        @Before
        public void init() {
            ...
        }
        @Test
        public void listCount() {
            ...
        }
    
        @Test
        public void useAppContext() {
            Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
    
            Assert.assertEquals("in.curioustools.aad_x_testing2", appContext.getPackageName());
            System.out.println("useAppContext : Test Ran");
        }
    }
    

    The thing that was bugging me was the fact that InstrumentationRegistery class was still deprecated. So i used InstrumentationRegistry.getInstrumentation().getTargetContext(); from androidx.test.platform.app.InstrumentationRegistry class.

提交回复
热议问题