Getting ready

We are going to use the JUnit library to provide a core framework for running test-case classes. We need to add it to our project's list of project dependencies by declaring it in the gradle.build script:

implementation group: 'junit', name: 'junit', version: '4.12'

In order to make use of the Kotlin Mockito library, we can add it to the project dependencies with the following declaration:

implementation 'com.nhaarman:mockito-kotlin:1.5.0'

You can examine the implementation and configuration of recipes related to the Android framework in the AndroidSamples project available in the GitHub repository: https://github.com/PacktPublishing/Kotlin-Standard-Library-Cookbook/. To follow Android-related recipes, you just need to create a new project in Android Studio.

In this recipe, we are going to write a unit test for the RegistrationFormController class, declared as follows:

class RegistrationForm(val api: RegistrationApi, val view: TextView) {
var currentEmailAddress: String by
Delegates.observable("", ::onEmailAddressNewValue)

fun onEmailAddressNewValue(prop: KProperty<*>, old: String,
new: String) {
if (checkIfEmailCanBeRegistered()) {
view.showSuccessMessage("Email address is available!")
} else {
view.showErrorMessage("This email address is not
available."
)
}
}

fun checkIfEmailCanBeRegistered(): Boolean =
isEmailIsValid() && api.isEmailAddressAvailable(currentEmailAddress)

fun isEmailIsValid(): Boolean = currentEmailAddress.contains("@")

}

It contains the RegistrationApi property which is defined as the following interface:

interface RegistrationApi {
fun isEmailAddressAvailable(email: String): Boolean
}

and the TextView type property defined as follows:

interface TextView {
fun showSuccessMessage(message: String)
fun showErrorMessage(message: String)
}

Since we don't want to implement the RegistrationApi and TextView interface in order to instantiate the RegistrationFormController class in our test, we are going to mock them using the Mockito Kotlin mock() function.

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

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