为 Android 设置 Roboelectric 测试。

3

我正在尝试为我的应用程序添加一些Roboelectric单元测试。使用Roboelectric 3.0,我希望能够测试我的活动PinActivity以及其中的片段。

import android.support.v7.app.AppCompatActivity;
import android.app.Fragment;

PinActivity extends AppCompatActivity {

Gradle文件包含:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    testCompile "org.robolectric:robolectric:3.0"
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

PinActivityTest包含:(编辑添加@Config未修复)

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;

import static org.junit.Assert.*;

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class PinActivityTest {

    @Test
    public void onCreate_shouldInflateLayout() throws Exception {
        PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get();
        assertNotNull(activity);
    }

目前收到以下警告:WARNING: No manifest file found at .\AndroidManifest.xml.Falling back to the Android OS resources only. To remove this warning, annotate your test class with @Config(manifest=Config.NONE).以及java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

为什么无法找到我的AndroidManifest文件? 有人知道如何解决这个问题或者有更多类似示例的Roboelectric教程吗?

1个回答

2
根据日志显示,您忘记了使用@Config注释,导致无法找到您的AndroidManifest文件:
请尝试以下操作:
@RunWith(RobolectricGradleTestRunner.class) 
@Config(constants = BuildConfig.class, sdk = 21) public class PinActivityTest {
    @Test
    public void onCreate_shouldInflateLayout() throws Exception {
        PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get();
        assertNotNull(activity);
    }

由于Roboelectric不支持API23及以上版本,因此我将测试SDK设置为API21。

编辑:还需更改:

    PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get()

to

    PinActivity activity = Robolectric.setupActivity(PinActivity.class);

注意:我的 Robolectric 依赖现在如下:

 testCompile("org.robolectric:robolectric:3.0") {
        exclude module: 'classworlds'
        exclude module: 'commons-logging'
        exclude module: 'httpclient'
        exclude module: 'maven-artifact'
        exclude module: 'maven-artifact-manager'
        exclude module: 'maven-error-diagnostics'
        exclude module: 'maven-model'
        exclude module: 'maven-project'
        exclude module: 'maven-settings'
        exclude module: 'plexus-container-default'
        exclude module: 'plexus-interpolation'
        exclude module: 'plexus-utils'
        exclude module: 'wagon-file'
        exclude module: 'wagon-http-lightweight'
        exclude module: 'wagon-provider-api'
    }

如果您有任何问题,请随时提出。希望这能帮到您。

1
原来我使用的是 @RunWith(RobolectricTestRunner.class) 而不是你建议的 @RunWith(RobolectricGradleTestRunner.class)。更改后问题得到解决。谢谢。 - J0B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接