Creating a Test Class
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
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.
Creating a Test Class
The most convenient way to write unit tests is within a testing framework. The framework makes it
easier to write and run a suite of tests together and see their output in Android Studio.
JUnit is almost universally used as a testing framework on Android and has convenient integrations
into Android Studio. Your first job is to create a class for your JUnit tests to live in. To do this, open
up SoundViewModel.java and key in Command+Shift+T (Ctrl+Shift+T). Android Studio attempts to