我将现有项目更新为 androidx,但出现 ExampleInstrumentedTest--> getTargetContext 错误
i updated my existing project to androidx but got ExampleInstrumentedTest--> getTargetContext error
当我将我的项目更新到 androidx 时,出现以下错误
我也搜索过但找不到我的答案,尽管项目工作正常
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.villagefoodsecrets", appContext.getPackageName());
}
}
此时,@RunWith(AndroidJUnit4.class)
表明它已被弃用。
和Context appContext = InstrumentationRegistry.getTargetContext();
.getTargetContext;红色格式看起来不存在。那么我可以在这里做什么 - 我应该忽略它吗?
要使用未弃用的 classes,请在下面添加 build.gradle(应用模块级别)
androidTestImplementation ‘androidx.test.ext:junit:1.1.1’
然后在 ExampleInstrumentedTest class
中替换以下已弃用的导入
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
和
import androidx.test.platform.app.InstrumentationRegistry ;
import androidx.test.ext.junit.runners.AndroidJUnit4;
并在下面使用上下文:
对于Java
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
对于 Kotlin
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
希望对您有所帮助
当我将我的项目更新到 androidx 时,出现以下错误
我也搜索过但找不到我的答案,尽管项目工作正常
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.villagefoodsecrets", appContext.getPackageName());
}
}
此时,@RunWith(AndroidJUnit4.class)
表明它已被弃用。
和Context appContext = InstrumentationRegistry.getTargetContext();
.getTargetContext;红色格式看起来不存在。那么我可以在这里做什么 - 我应该忽略它吗?
要使用未弃用的 classes,请在下面添加 build.gradle(应用模块级别)
androidTestImplementation ‘androidx.test.ext:junit:1.1.1’
然后在 ExampleInstrumentedTest class
中替换以下已弃用的导入import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
和
import androidx.test.platform.app.InstrumentationRegistry ;
import androidx.test.ext.junit.runners.AndroidJUnit4;
并在下面使用上下文:
对于Java
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
对于 Kotlin
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
希望对您有所帮助