为Android设置Roboelectric测试

时间:2016-01-12 21:00:25

标签: java android junit robolectric

我正在尝试为我的应用添加一些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 个答案:

答案 0 :(得分: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设置为API 21。

编辑:改变:

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

    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'
    }

如果您有任何疑问,请随意提问。

希望有所帮助