关注有关单元测试和失败的Android文档

问题描述

我试图通过遵循此处的示例来运行简单的单元测试:

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.

但是,这在文档中被列为本地单元测试而不是仪器化测试。

解决方法

这对于有经验的人来说是常识,但是我会为那些像我这样刚起步的人写的。

许多唯一的教程非常混乱,由于所有内容的不同版本,我无法使它们编译或工作。

我没有意识到的第一件事是有两个不同的Gradle函数,分别是testImplementation和androidTestImplementation。函数“ testImplementation”用于普通的单元测试,函数“ androidTestImplementation”用于仪表化的单元测试(单元测试,但在物理设备上运行)。

因此,当您在Gradle中看到依赖项下的命令时:

testImplementation 'junit:junit:4.12'

仅在默认app / src / test文件夹中包含用于单元测试的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级别30。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...