我试图将上下文传递到一个单元测试的构造函数中。我得到以下错误
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);
}
}
在AndroidJUnit runner中添加@RunWith注解。
@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'