Java 在扩展TestCase的类中找不到上下文
我正在为android应用程序类编写测试用例。但我无法找到一种方法来获取这个类的上下文。下面是我的测试用例类Java 在扩展TestCase的类中找不到上下文,java,android,android-testing,testcase,Java,Android,Android Testing,Testcase,我正在为android应用程序类编写测试用例。但我无法找到一种方法来获取这个类的上下文。下面是我的测试用例类 public class SplashScreenActivityTest extends TestCase { SplashScreenActivity splashScreenActivity; Context context; public void setUp() throws Exception { super.setUp();
public class SplashScreenActivityTest extends TestCase {
SplashScreenActivity splashScreenActivity;
Context context;
public void setUp() throws Exception {
super.setUp();
splashScreenActivity = new SplashScreenActivity();
}
public void testDeviceDetailsPost() throws Exception {
//I need to access a method here which requires context
}
}
我看了很多问题,但我不明白他们的答案
比如这个问题
您可以将实例变量
context
传递给需要它的方法,如下所示methodthatRequiredContext(context)代码>
我不完全确定您的困难是什么。您可以使用AndroidTestCase,这个类有getContext()方法
或者创建没有父级的类,并将@RunWith(AndroidJUnit4.class)添加到类头中。并使用以下命令:InstrumentationRegistry.getTargetContext()
提醒:我必须把这个测试类放到androidTest包中,因为这个类有集成测试。了解Android测试的良好起点
培训(谷歌官方文档)
存储库包含不同类型测试的示例
AndroidTestCase已被弃用上下文必须包含上下文仅创建变量并将其传递给方法将不起作用;