如何获得单元测试的上下文

问题描述 投票:0回答:1

我试图将上下文传递到一个单元测试的构造函数中。我得到以下错误

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);

    }
}
java android android-testing
1个回答
0
投票

在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'
© www.soinside.com 2019 - 2024. All rights reserved.