我尝试按照下面的示例运行简单的单元测试:
https://developer.android.com/training/testing/unit-testing/local-unit-tests
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Test;
import static com.google.common.truth.Truth.assertThat;
public class UnitTestSampleJava {
private static final String FAKE_STRING = "HELLO_WORLD";
private Context context = ApplicationProvider.getApplicationContext();
@Test
public void readStringFromContext_LocalizedString() {
// Given a Context object retrieved from Robolectric...
ClassUnderTest myObjectUnderTest = new ClassUnderTest(context);
// ...when the string is returned from the object under test...
String result = myObjectUnderTest.getHelloWorldString();
// ...then the result should be the expected one.
assertThat(result).isEqualTo(FAKE_STRING);
}
}我有一个全新的项目,我按照指定的方式设置了gradle文件,然后我用下面的代码行创建了一个测试:
private Context context = ApplicationProvider.getApplicationContext();我在那个行号上得到了一个异常,声明:
java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.但是,这在文档中被列为本地单元测试,而不是仪表化测试。
发布于 2020-08-18 01:34:29
这将是有经验的人的常识,但我将为像我这样刚刚起步的人写这篇文章。
许多仅有的教程非常令人困惑,我无法让它们编译或工作,因为所有东西的版本都不同。
我没有意识到的第一件事是有两个不同的Gradle函数,testImplementation和androidTestImplementation。函数"testImplementation“用于普通单元测试,函数"androidTestImplementation”用于仪表化单元测试(单元测试,但在物理设备上运行)。
因此,当您在Gradle中的依赖项下看到该命令时:
testImplementation 'junit:junit:4.12'这只包括默认app/src/ JUnit文件夹中单元测试的测试4.12,而不是app/src/androidTest文件夹。
如果你按照我上面链接的教程(可能是过时的或者根本就是不正确的)是'androidx.test:core:1.0.0‘集成了Robolectric,并且你使用的是Robolectric而没有调用函数或者直接导入。
您不需要添加@RunWith注释,因为在Gradle文件中,本教程会添加:
defaultConfig {
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
...
}尽管如此,我还是无法通过遵循教程来逃脱我所描述的异常。所以我不得不直接包含Robolectric:
testImplementation "org.robolectric:robolectric:4.3.1"这是我的单元测试类:
import android.content.Context;
import androidx.test.core.app.ApplicationProvider;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.junit.Assert.assertTrue;
@Config(maxSdk = 29)
@RunWith(RobolectricTestRunner.class)
public class UnitTestSample {
private static final String FAKE_STRING = "HELLO_WORLD";
@Test
public void clickingButton_shouldChangeResultsViewText() throws Exception {
Context context = ApplicationProvider.getApplicationContext();
assertTrue(true);
}
}我必须做的另一件事是使用@Config将SDK设置为29,因为Robolectric 4.3.1不支持Android API level 30。
https://stackoverflow.com/questions/63440421
复制相似问题