4

I use abstract activity classes in my code to well, abstract away some features from the activity classes.

I'm trying to test the abstract activity classes using Robolectric and the gradle-android-test-plugin using subclasses that extend the abstract class. I can't seem to get it to work though.

Does anyone have any experience in this area and is it even possible ? Basic structure is :

@RunWith(RobolectricGradleTestRunner.class)
public class AbstractActivityTest {
    private ActivityTest activity;

    @Before
    public void setUp() throws Exception {
        activity = Robolectric.buildActivity(ActivityTest.class).create().get();
    }


    private class ActivityTest extends AbstractActivity {
        // do something
    }
}

Initially, I got the error message the sub class wasn't static so I made it static. Now I get the following two fails:

initializationError FAILED
java.lang.Exception: Test class should have exactly one public constructor

initializationError FAILED
java.lang.Exception: No runnable methods

Any obviously true tests I put in @Test methods succeed.

4

3 回答 3

5

第一个错误表明您向测试类添加了非默认构造函数或更改了默认构造函数的访问级别。但正如它所说,junitTest 类应该至少有一个公共构造函数。

第二个说测试类中至少有一个方法应该有@Test注释(junit 4)或以测试子字符串(junit 3)开头。

于 2013-09-10T08:29:31.743 回答
3

你可以做你想做的事:子类化抽象活动并实例化具体类。

但是,您需要在其自己的公共文件中声明扩展抽象 Activity 的类。如果它是一个嵌套类 Robolectric 将无法实例化它。

不过,我不知道为什么。

于 2014-04-10T12:06:09.023 回答
0

我以这种方式测试一个抽象活动:

1.创建抽象的活动:

public abstract class AbstractActivity extends AppCompatActivity {

    public int getNumber() {
        return 2;
    }
}

2. 创建测试类:
你只需要声明一个抽象类的静态嵌套子类。

@RunWith(RobolectricTestRunner.class)
public class AbstractActivityTest {

    @Test
    public void checkNumberReturn() throws Exception {
        TestAbstractActivity testAbstractActivity = Robolectric.setupActivity(TestAbstractActivity.class);
        assertThat(testAbstractActivity.getNumber(), is(2));
    }

    public static class TestAbstractActivity extends AbstractActivity {
    }
}
于 2018-01-28T17:22:53.487 回答