Test Dependencies

Before you write your test, you will need to add a couple of tools to your testing environment: Mockito and Hamcrest. Mockito is a Java framework that makes it easy to create simple mock objects. These mock objects will help you isolate your tests of SoundViewModel so that you do not accidentally test other objects at the same time.

Hamcrest, on the other hand, is a library of matchers. Matchers are tools that make it easy to match conditions in your code and fail if your code does not match what you expect. You will use them to verify that your code works as you expect it to.

You only need these two libraries in your test builds, so you will add them as test dependencies. Start by right-clicking your app module and selecting Open Module Settings.

Select the Dependencies tab at the top of the screen, click the + button at the bottom of the dialog, and choose Library dependency. Type in mockito and press Return to search (Figure 21.1).

Figure 21.1  Importing Mockito

Screenshot shows Choose Library Dependency window. A list of dependencies is displayed below a search bar. Cancel and OK buttons are placed below.

Select the org.mockito:mockito-core dependency and click OK. Then repeat the process for Hamcrest, searching for hamcrest-junit and selecting org.hamcrest:hamcrest-junit.

Once you finish, you will see your two new dependencies appear in the dependencies list. There is a dropdown on the right-hand side of the mockito-core and hamcrest-junit dependencies. This dropdown allows you to choose between different dependency scopes. It only allows you to specify integration test scope, though, so you will need to modify your build.gradle by hand.

Open your app module’s build.gradle and modify the dependency directives from compile to testCompile.

Listing 21.6  Changing scope of Mockito dependency (app/build.gradle)

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.0'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:recyclerview-v7:24.2.0'
    compile testCompile 'org.mockito:mockito-core:2.2.1'
    compile testCompile 'org.hamcrest:hamcrest-junit:2.0.0.0'
}

The testCompile scope means that these two dependencies will only be included in test builds of your app. That way, you do not bloat your APK with additional unused code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.61.223