Tag Archives: java

Testing on Android part 1: Unit testing

Hello fellas! The last article received a lot of positive feedbacks and questions. I noticed that most of the questions was related to tests, specially about unit testing on Android. I admit that testing could be tricky at first. There are too many option and approaches to choose from and one could get lost trying to pick the right one.

In this series we’ll talk about:

  • Different kinds of tests and when to use then
    • Unit tests
    • Integration tests
    The most common frameworks available on Android
    • JUnit4, Robolectric, Espresso, Mockito and Hamcrest Matchers
    How to setup the test environment How to create unit and instrumental tests How to run the tests =&0=&
    dependencies {
        //...
        testCompile 'junit:junit:4.12'
        testCompile 'org.hamcrest:hamcrest-library:1.1'
        testCompile "org.robolectric:robolectric:3.0"
        testCompile 'org.mockito:mockito-core:1.10.19'
    }

    2. Create this folder structure: /src/test/java/ [package-name]

    3. Click on “Build Variants” and in “Test Artifacts” select “Unit Tests

    Selection Unit Tests
    Selecting Unit Tests in Android Studio

    Creating a Test configuration

    1. Click “Edit Configurations…”
    Click on "Edit Configurations"
    Click on “Edit Configurations…”

    2. Click on “+” and select JUnit

     Click on "+" and select JUnit
    Click on “+” and select JUnit

    3. Give it a name and in “Tesk Kind” select “All in Package”

    Give it a nem and In "Test Kind" select "All in Package"
    Give it a nem and In “Test Kind” select “All in Package”

    4. To run Robolectric you need to select “$MODULE_DIR$” in “Working Directory”

    in "Working Directory" select "$MODULE_DIR$"
    To run Robolectric you need to select “$MODULE_DIR$” in “Working Directory”

    Building our Unit Tests

    In our tests we’ll use a app developed using MVP architecture pattern. It consists of a basic note taker with only one Activity working as a passive View, a Presenter working as a middle man and a Model containing all data business logic. We’ll consider that you domains all concepts adopted on the application, so we’ll concentrate only on the tests. Fell free to clone the repository

    Testing the database

    Let’s consider that we just created our SQLiteOpenHelper class. Now we want to test it to see if it is working correctly before proceeding.

    Our test class should be inserted in the test package created earlier.

    @RunWith(RobolectricGradleTestRunner.class)
    // To use Robolectric you'll need to setup some constants.
    // Change it according to your needs.
    @Config(constants = BuildConfig.class, sdk = 21, manifest = "/src/main/AndroidManifest.xml")
    public class DBSchemaTest {
    
        private Context context;
        private DBSchema helper;
    }

    leia mais