Home Tutorials Training Consulting Products Books Company Donate Contact us









NOW Hiring

Quick links

Share

This tutorial describes how to write unit test for Android applications with the Robolectric frameworks. This tutorial describes how to write unit and instrumentation tests for your Android application.

1. Robolectric

1.1. What is Robolectric

Robolectric is designed to allow you to test Android applications on the JVM based on the JUnit 4 framework. Robolectric is a framework that allows you to write unit tests and run them on a desktop JVM while still using Android API. Robolectric mocks part of the Android framework contained in the android.jar file. Robolectric provides also implementations for the methods while the standard Android unit testing support throws exceptions for all Android methods.

This enables you to run your Android tests in your continuous integration environment without any additional setup. Robolectric supports resource handling, e.g., inflation of views. You can also use the findViewById() to search in a view.

The homepage of Robolectric under the following URL: http://robolectric.org.

Robolectric is not an integration test framework, i.e., you cannot not test the interaction of Android components with it.

1.2. Shadow objects

Robolectric replaced all Android classes by so-called shadow objects. If a method is implemented by Robolectric,it forwards these method calls to the shadow object. Shadow objects behave similar to the Android implementation. If a method is not implemented by the shadow object, it simply returns a default value, e.g., null or 0.

To access a shadow object use Shadows.shadowOf.

2. Using Robolectric for your test with Gradle

To use Robolectric for your Android unit tests, simply add the following dependency to your Gradle build file.

dependencies {
    ...
    // Robolectric
    testCompile "org.robolectric:robolectric:3.0"
}

Your tests should be stored in the src/test directory. The class containing your Robolectric test must be annotate with the @RunWith(RobolectricGradleTestRunner.class) test runner. It must also use the @Config() to point to your BuildConfig.class class. The following shows an example test configured to run via Robolectric on the JVM.

package com.vogella.android.test.robolectric;

import com.vogella.android.test.robolectric.BuildConfig;
import com.vogella.android.test.robolectric.R;
import com.vogella.android.test.robolectric.WelcomeActivity;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertNotNull;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)

public class WelcomeActivityTest
{
    private WelcomeActivity activity;

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

    @Test
    public void shouldNotBeNull() throws Exception
    {
        assertNotNull( activity );
    }

    @Test
    public void shouldHaveWelcomeFragment() throws Exception
    {
        assertNotNull( activity.getFragmentManager().findFragmentById( R.id.welcome_fragment ) );
    }
}

Instead of specifying the values via the @Config annotation, you could also use a resources/robolectric.properties file. See See http://robolectric.org/configuring for more information.

3. Roboelectric test

The following code is an example for a few Robolectric tests.

package com.vogella.android.test.robolectric;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import com.example.BuildConfig;
import com.example.R;
import com.example.SecondActivity;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.shadows.ShadowToast;

import android.content.Intent;
import android.widget.Button;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MyActivityTest {

        private MainActivity activity;

        @Test
        public void shouldHaveHappySmiles() throws Exception {
                String hello = new MainActivity().getResources().getString(
                                R.string.hello_world);
                assertThat(hello, equalTo("Hello world!"));
        }

        @Before
        public void setup()  {
                activity = Robolectric.buildActivity(MainActivity.class)
                                .create().get();
        }
        @Test
        public void checkActivityNotNull() throws Exception {
                assertNotNull(activity);
        }

        @Test
        public void buttonClickShouldStartNewActivity() throws Exception
        {
            Button button = (Button) activity.findViewById( R.id.button2 );
            button.performClick();
            Intent intent = Shadows.shadowOf(activity).peekNextStartedActivity();
            assertEquals(SecondActivity.class.getCanonicalName(), intent.getComponent().getClassName());
        }

        @Test
        public void testButtonClick() throws Exception {
                MainActivity activity = Robolectric.buildActivity(MainActivity.class)
                                .create().get();
                Button view = (Button) activity.findViewById(R.id.button1);
                assertNotNull(view);
                view.performClick();
                assertThat(ShadowToast.getTextOfLatestToast(), equalTo("Lala") );
        }

}

4. About this website

5. Robolectric resources

5.1. vogella GmbH training and consulting support

TRAINING SERVICE & SUPPORT

The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”.

The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.

Copyright © 2012-2016 vogella GmbH. Free use of the software examples is granted under the terms of the EPL License. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.

See Licence.