Android test suite using robolectric?


I’m trying to search for an example of how to run a tests suite for test classes that use Robolectric, for example I have this class:

@Config(sdk  16, manifest  "src/main/AndroidManifest.xml")
public class RestaurantModelTest {

    //setUp code here...

    public void testFindByLocation() throws Exception {
         //test code here


All unit test and assertions of class RestaurantModelTest are passing, but I also have another class lets call it XModelTest (in which all assertions and unit test are passing.

My problem

I don’t find any tutorial/example of how to use a test suite using robolectric.

Should this be done in the same package where my RestaurantModelTest and XModelTest are? If not where?

Also I tried doing this with TestSuite from JUnit but many questions arise should the class with my TestSuite extend extends TestSuite super class?

If someone can give me a short example using my RestaurantModelTestand XModelTestclasses it would be great.


I believe, I’ve also partially covered this question answering your second question – Can’t run android test suite: Exception in thread “main”

Here’s how to write a suite with Robolectric: Let’s say we have 2 model classes.

public class CartModel {
    public float totalAmount;
    public int products;

    public void addToCart(float productPrice) {
        totalAmount + productPrice;


public class RestaurantModel {    
    public int staff;

    public void hire(int numberOfHires) {
        staff + numberOfHires;

Let’s write some dummy tests for them:

@Config(constants  BuildConfig.class, sdk21)
public class CartModelTest {

    public void addToCart() throws Exception {
        CartModel cartModel  new CartModel();
        assertEquals(0, cartModel.totalAmount, 0);
        assertEquals(0, cartModel.products);
        assertEquals(10.2f, cartModel.totalAmount, 0);
        assertEquals(1, cartModel.products);

@Config(constants  BuildConfig.class, sdk21)
public class RestaurantModelTest {

    public void hire() throws Exception {
        RestaurantModel restaurantModel  new RestaurantModel();
        assertEquals(0, restaurantModel.staff);
        assertEquals(1, restaurantModel.staff);

And now last step – to group them together into one

public class ModelsTestSuite {}

To run – just right-click in ModelsTestSuite and click “Run ModelsTestSuite”. That’s it!

NB! In Android Studio 2.0 3b, you have to disable instant run (Preferences -> Build, Execution, Deployment -> Instant Run -> Enable Instant Run – uncheck) in order to run Robolectric tests (to avoid java.lang.RuntimeException: java.lang.ClassNotFoundException: Could not find a class for package: <package name> and class name:

I hope, it helps

Answered By – Konstantin Loginov

Leave a Comment