如何获取单元测试的上下文
How to get Context for Unit Test
我正在尝试将上下文传递到构造函数中以进行单元测试。我收到以下错误
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
我试过下面的代码。
public class Handler {
@Mock
MyViewModel viewModel;
@Before
public void setup() {
Context context = InstrumentationRegistry.getInstrumentation().getContext();
Handler = new Handler(context, viewModel);
}
}
Add @RunWith annotation with AndroidJUnit runner.
@RunWith(AndroidJunit4::class)
public class Handler {
@Mock
MyViewModel viewModel;
@Before
public void setup() {
Context context = InstrumentationRegistry.getInstrumentation().getContext();
Handler = new Handler(context, viewModel);
}
}
如果 build.gradle(app)
中没有添加下面的依赖,还要添加
androidTestImplementation 'androidx.test.ext:junit:1.0.0'
我正在尝试将上下文传递到构造函数中以进行单元测试。我收到以下错误
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
我试过下面的代码。
public class Handler {
@Mock
MyViewModel viewModel;
@Before
public void setup() {
Context context = InstrumentationRegistry.getInstrumentation().getContext();
Handler = new Handler(context, viewModel);
}
}
Add @RunWith annotation with AndroidJUnit runner.
@RunWith(AndroidJunit4::class)
public class Handler {
@Mock
MyViewModel viewModel;
@Before
public void setup() {
Context context = InstrumentationRegistry.getInstrumentation().getContext();
Handler = new Handler(context, viewModel);
}
}
如果 build.gradle(app)
中没有添加下面的依赖,还要添加androidTestImplementation 'androidx.test.ext:junit:1.0.0'