Is it possible to test an Abstract activity with Robolectric

十年热恋 提交于 2019-12-23 12:43:27

问题


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.


回答1:


The first error saying that you added non-default constructor to your test class or changed access level for default one. But as it says junit Test class should have at least one public constructor.

The second one says that at least one method in test class should have @Test annotation (junit 4) or starts with test substring (junit 3).




回答2:


Yo can doing exactly what you are trying to do: subclass the abstract activity and instance the concrete class.

However, you need to declare the class extending the abstract Activity in it's own public file. If it's a nested class Robolectric will fail to instance it.

I don't know why, though.




回答3:


I test an abstract activity this way:

1. Creating the abstract avtivity:

public abstract class AbstractActivity extends AppCompatActivity {

    public int getNumber() {
        return 2;
    }
}

2. Creating the test class:
You just need to declare a static nested subclass of your abstract class.

@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 {
    }
}


来源:https://stackoverflow.com/questions/18558927/is-it-possible-to-test-an-abstract-activity-with-robolectric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!