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 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.

A version of Hamcrest is automatically included with the JUnit library, and JUnit is automatically included as a dependency when you create a new Android Studio project. This means that you only need to add the dependencies for Mockito to your test build. Open your app module’s build.gradle file and add the Mockito dependencies (Listing 20.6). Sync your files when you are done.

Listing 20.6  Adding Mockito dependencies (app/build.gradle)

dependencies {
    ...
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    testImplementation 'org.mockito:mockito-core:2.25.0'
    testImplementation 'org.mockito:mockito-inline:2.25.0'
}

The testImplementation scope means that this dependency will only be included in test builds of your app. That way, you do not bloat your APK with additional unused code.

mockito-core includes all of the functions you will use to create and configure your mock objects. mockito-inline is a special dependency that will make Mockito easier to use with Kotlin.

By default, all Kotlin classes are final. This means that you cannot inherit from these classes unless you explicitly mark them as open. Unfortunately, Mockito makes heavy use of inheritance when mocking classes. This means that Mockito cannot mock your Kotlin classes out of the box. The mockito-inline dependency includes functionality that allows Mockito to mock final classes and functions, working around this inheritance problem. This allows you to mock your Kotlin classes without needing to change your source files.

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

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