简体   繁体   中英

Is it possible to test an Abstract activity with Robolectric

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.

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 ).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM