forked from android/testing-samples
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Kotlin version of Basic Unit Tests sample.
- Loading branch information
Showing
28 changed files
with
1,116 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
# Basic sample (in Kotlin) for writing unit tests that mocks the Android framework | ||
|
||
*If you are new to unit testing on Android, try this sample first.* | ||
|
||
This project uses the Gradle build system and the Android gradle plugin support for unit testing. | ||
You can either benefit from IDEs integration such as Android studio or run the tests on the command | ||
line. | ||
|
||
Unit tests run on a local JVM on your development machine. The Android Gradle plugin will compile | ||
your app's source code and execute it using gradle test task. Tests are executed against a modified | ||
version of android.jar where all final modifiers have been stripped off. This lets you use popular | ||
mocking libraries, like Mockito. | ||
|
||
For more information see http://tools.android.com/tech-docs/unit-testing-support | ||
|
||
## Setup the project in Android studio and run tests. | ||
|
||
1. Download the project code, preferably using `git clone`. | ||
1. In Android Studio, select *File* | *Open...* and point to the `./build.gradle` file. | ||
1. Make sure you select "Unit Tests" as the test artifact in the "Build Variants" panel in Android Studio. | ||
1. Check out the relevant code: | ||
* The application code is located in `src/main/java` | ||
* Unit Tests are in `src/test/java` | ||
1. Create a test configuration with the JUnit4 runner: `org.junit.runners.JUnit4` | ||
* Open *Run* menu | *Edit Configurations* | ||
* Add a new *JUnit* configuration | ||
* Choose module *app* | ||
* Select the class to run by using the *...* button | ||
1. Run the newly created configuration | ||
|
||
The unit test will be ran automatically. | ||
|
||
## Use Gradle on the command line. | ||
|
||
After downloading the projects code using `git clone` you'll be able to run the | ||
unit tests using the command line: | ||
|
||
./gradlew test | ||
|
||
If all the unit tests have been successful you will get a `BUILD SUCCESSFUL` | ||
message. | ||
|
||
## See the report. | ||
|
||
A report in HTML format is generated in `app/build/reports/tests` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
apply plugin: 'com.android.application' | ||
|
||
apply plugin: 'kotlin-android' | ||
|
||
apply plugin: 'kotlin-android-extensions' | ||
|
||
android { | ||
compileSdkVersion 27 | ||
defaultConfig { | ||
applicationId "com.example.android.testing.unittesting.BasicSample" | ||
minSdkVersion 14 | ||
versionCode 1 | ||
versionName "1.0" | ||
targetSdkVersion 27 | ||
} | ||
} | ||
|
||
dependencies { | ||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlinVersion" | ||
|
||
// Unit testing dependencies. | ||
testImplementation 'junit:junit:4.12' | ||
testImplementation 'org.mockito:mockito-core:2.8.9' | ||
} |
35 changes: 35 additions & 0 deletions
35
unit/BasicSample-kotlinApp/app/src/main/AndroidManifest.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<!-- | ||
~ Copyright (C) 2015 The Android Open Source Project | ||
~ | ||
~ Licensed under the Apache License, Version 2.0 (the "License"); | ||
~ you may not use this file except in compliance with the License. | ||
~ You may obtain a copy of the License at | ||
~ | ||
~ http://www.apache.org/licenses/LICENSE-2.0 | ||
~ | ||
~ Unless required by applicable law or agreed to in writing, software | ||
~ distributed under the License is distributed on an "AS IS" BASIS, | ||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
~ See the License for the specific language governing permissions and | ||
~ limitations under the License. | ||
--> | ||
|
||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" | ||
package="com.example.android.testing.unittesting.BasicSample" > | ||
|
||
<application | ||
android:icon="@drawable/ic_launcher" | ||
android:label="@string/app_name" | ||
android:theme="@style/AppTheme" > | ||
<activity | ||
android:name="com.example.android.testing.unittesting.BasicSample.MainActivity" | ||
android:label="@string/app_name" > | ||
<intent-filter> | ||
<action android:name="android.intent.action.MAIN" /> | ||
<category android:name="android.intent.category.LAUNCHER" /> | ||
</intent-filter> | ||
</activity> | ||
</application> | ||
|
||
</manifest> |
64 changes: 64 additions & 0 deletions
64
...p/app/src/main/java/com/example/android/testing/unittesting/BasicSample/EmailValidator.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/* | ||
* Copyright (C) 2017 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.example.android.testing.unittesting.BasicSample | ||
|
||
import android.text.Editable | ||
import android.text.TextWatcher | ||
|
||
import java.util.regex.Pattern | ||
|
||
/** | ||
* An Email format validator for [android.widget.EditText]. | ||
*/ | ||
class EmailValidator : TextWatcher { | ||
|
||
internal var isValid = false | ||
|
||
override fun afterTextChanged(editableText: Editable) { | ||
isValid = isValidEmail(editableText) | ||
} | ||
|
||
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) = Unit | ||
|
||
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = Unit | ||
|
||
companion object { | ||
|
||
/** | ||
* Email validation pattern. | ||
*/ | ||
private val EMAIL_PATTERN = Pattern.compile( | ||
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + | ||
"\\@" + | ||
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + | ||
"(" + | ||
"\\." + | ||
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + | ||
")+" | ||
) | ||
|
||
/** | ||
* Validates if the given input is a valid email address. | ||
* | ||
* @param email The email to validate. | ||
* @return `true` if the input is a valid email, `false` otherwise. | ||
*/ | ||
fun isValidEmail(email: CharSequence?): Boolean { | ||
return email != null && EMAIL_PATTERN.matcher(email).matches() | ||
} | ||
} | ||
} |
125 changes: 125 additions & 0 deletions
125
...App/app/src/main/java/com/example/android/testing/unittesting/BasicSample/MainActivity.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
/* | ||
* Copyright (C) 2017 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.example.android.testing.unittesting.BasicSample | ||
|
||
import android.app.Activity | ||
import android.content.SharedPreferences | ||
import android.os.Bundle | ||
import android.preference.PreferenceManager | ||
import android.util.Log | ||
import android.view.View | ||
import android.widget.DatePicker | ||
import android.widget.EditText | ||
import android.widget.Toast | ||
import java.util.Calendar | ||
|
||
/** | ||
* An [Activity] that represents an input form page where the user can provide their name, date | ||
* of birth, and email address. The personal information can be saved to [SharedPreferences] | ||
* by clicking a button. | ||
*/ | ||
class MainActivity : Activity() { | ||
|
||
private val TAG = "MainActivity" | ||
|
||
// The helper that manages writing to SharedPreferences. | ||
private lateinit var sharedPreferencesHelper: SharedPreferencesHelper | ||
|
||
// The input field where the user enters their name. | ||
private lateinit var nameText: EditText | ||
|
||
// The date picker where the user enters their date of birth. | ||
private lateinit var dobPicker: DatePicker | ||
|
||
// The input field where the user enters their email. | ||
private lateinit var emailText: EditText | ||
|
||
// The validator for the email input field. | ||
private var emailValidator = EmailValidator() | ||
|
||
override fun onCreate(savedInstanceState: Bundle?) { | ||
super.onCreate(savedInstanceState) | ||
setContentView(R.layout.activity_main) | ||
|
||
// Shortcuts to input fields. | ||
nameText = findViewById(R.id.userNameInput) | ||
dobPicker = findViewById(R.id.dateOfBirthInput) | ||
emailText = findViewById(R.id.emailInput) | ||
|
||
// Setup email field validator. | ||
emailText.addTextChangedListener(emailValidator) | ||
|
||
// Instantiate a SharedPreferencesHelper. | ||
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) | ||
sharedPreferencesHelper = SharedPreferencesHelper(sharedPreferences) | ||
|
||
// Fill input fields from data retrieved from the SharedPreferences. | ||
populateUi() | ||
} | ||
|
||
/** | ||
* Initialize all fields from the personal info saved in the SharedPreferences. | ||
*/ | ||
private fun populateUi() { | ||
val sharedPreferenceEntry = sharedPreferencesHelper.getPersonalInfo() | ||
nameText.setText(sharedPreferenceEntry.name) | ||
val dateOfBirth = sharedPreferenceEntry.dateOfBirth | ||
dobPicker.init(dateOfBirth.get(Calendar.YEAR), dateOfBirth.get(Calendar.MONTH), | ||
dateOfBirth.get(Calendar.DAY_OF_MONTH), null) | ||
emailText.setText(sharedPreferenceEntry.email) | ||
} | ||
|
||
/** | ||
* Called when the "Save" button is clicked. | ||
*/ | ||
fun onSaveClick(@Suppress("UNUSED_PARAMETER") view: View) { | ||
// Don't save if the fields do not validate. | ||
if (!emailValidator.isValid) { | ||
emailText.error = "Invalid email" | ||
Log.w(TAG, "Not saving personal information: Invalid email") | ||
return | ||
} | ||
|
||
// Get the text from the input fields. | ||
val name = nameText.text.toString() | ||
val dateOfBirth = Calendar.getInstance() | ||
dateOfBirth.set(dobPicker.year, dobPicker.month, dobPicker.dayOfMonth) | ||
val email = emailText.text.toString() | ||
|
||
// Create a Setting model class to persist. | ||
val sharedPreferenceEntry = SharedPreferenceEntry(name, dateOfBirth, email) | ||
|
||
// Persist the personal information. | ||
val isSuccess = sharedPreferencesHelper.savePersonalInfo(sharedPreferenceEntry) | ||
if (isSuccess) { | ||
Toast.makeText(this, "Personal information saved", Toast.LENGTH_LONG).show() | ||
Log.i(TAG, "Personal information saved") | ||
} else { | ||
Log.e(TAG, "Failed to write personal information to SharedPreferences") | ||
} | ||
} | ||
|
||
/** | ||
* Called when the "Revert" button is clicked. | ||
*/ | ||
fun onRevertClick(@Suppress("UNUSED_PARAMETER") view: View) { | ||
populateUi() | ||
Toast.makeText(this, "Personal information reverted", Toast.LENGTH_LONG).show() | ||
Log.i(TAG, "Personal information reverted") | ||
} | ||
|
||
} |
24 changes: 24 additions & 0 deletions
24
...rc/main/java/com/example/android/testing/unittesting/BasicSample/SharedPreferenceEntry.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/* | ||
* Copyright (C) 2017 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.example.android.testing.unittesting.BasicSample | ||
|
||
import java.util.Calendar | ||
|
||
/** | ||
* Model class containing personal information that will be saved to SharedPreferences. | ||
*/ | ||
class SharedPreferenceEntry(val name: String, val dateOfBirth: Calendar, val email: String) |
70 changes: 70 additions & 0 deletions
70
.../main/java/com/example/android/testing/unittesting/BasicSample/SharedPreferencesHelper.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
/* | ||
* Copyright (C) 2017 The Android Open Source Project | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
package com.example.android.testing.unittesting.BasicSample | ||
|
||
import android.content.SharedPreferences | ||
import java.util.Calendar | ||
|
||
/** | ||
* Helper class to manage access to [SharedPreferences]. | ||
* | ||
* @param sharedPreferences The injected [SharedPreferences] that will be used in this DAO. | ||
*/ | ||
class SharedPreferencesHelper(private val sharedPreferences: SharedPreferences) { | ||
|
||
/** | ||
* Retrieves the [SharedPreferenceEntry] containing the user's personal information from | ||
* [SharedPreferences]. | ||
* | ||
* @return the Retrieved [SharedPreferenceEntry]. | ||
*/ | ||
// Get data from the SharedPreferences. | ||
// Create and fill a SharedPreferenceEntry model object. | ||
fun getPersonalInfo(): SharedPreferenceEntry { | ||
val name = sharedPreferences.getString(KEY_NAME, "") | ||
val dobMillis = sharedPreferences.getLong(KEY_DOB, Calendar.getInstance().timeInMillis) | ||
val dateOfBirth = Calendar.getInstance().apply { timeInMillis = dobMillis } | ||
val email = sharedPreferences.getString(KEY_EMAIL, "") | ||
return SharedPreferenceEntry(name, dateOfBirth, email) | ||
} | ||
|
||
/** | ||
* Saves the given [SharedPreferenceEntry] that contains the user's settings to | ||
* [SharedPreferences]. | ||
* | ||
* @param sharedPreferenceEntry contains data to save to [SharedPreferences]. | ||
* @return `true` if writing to [SharedPreferences] succeeded, `false` otherwise. | ||
*/ | ||
fun savePersonalInfo(sharedPreferenceEntry: SharedPreferenceEntry): Boolean { | ||
// Start a SharedPreferences transaction. | ||
val editor = sharedPreferences.edit().apply() { | ||
putString(KEY_NAME, sharedPreferenceEntry.name) | ||
putLong(KEY_DOB, sharedPreferenceEntry.dateOfBirth.timeInMillis) | ||
putString(KEY_EMAIL, sharedPreferenceEntry.email) | ||
} | ||
|
||
// Commit changes to SharedPreferences. | ||
return editor.commit() | ||
} | ||
|
||
companion object { | ||
// Keys for saving values in SharedPreferences. | ||
internal val KEY_NAME = "key_name" | ||
internal val KEY_DOB = "key_dob_millis" | ||
internal val KEY_EMAIL = "key_email" | ||
} | ||
} |
Binary file added
BIN
+3.83 KB
unit/BasicSample-kotlinApp/app/src/main/res/drawable-hdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+2.23 KB
unit/BasicSample-kotlinApp/app/src/main/res/drawable-mdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+4.97 KB
unit/BasicSample-kotlinApp/app/src/main/res/drawable-xhdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+7.9 KB
unit/BasicSample-kotlinApp/app/src/main/res/drawable-xxhdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added
BIN
+11 KB
unit/BasicSample-kotlinApp/app/src/main/res/drawable-xxxhdpi/ic_launcher.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Oops, something went wrong.