├── .gitattributes
├── .gitignore
├── LICENSE
├── LICENSE_HEADER
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ ├── kotlin
│ │ └── com
│ │ │ └── example
│ │ │ └── unittesting
│ │ │ ├── BasePresenter.kt
│ │ │ ├── Presenter.kt
│ │ │ ├── ResourceProvider.kt
│ │ │ ├── SchedulersFactory.kt
│ │ │ └── login
│ │ │ ├── model
│ │ │ ├── LoginCredentials.kt
│ │ │ ├── LoginRepository.kt
│ │ │ ├── LoginUseCase.kt
│ │ │ └── LoginValidator.kt
│ │ │ ├── presenter
│ │ │ ├── LoginPresenter.kt
│ │ │ └── LoginView.kt
│ │ │ └── view
│ │ │ └── LoginActivity.kt
│ └── res
│ │ ├── layout
│ │ └── activity_login.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ ├── kotlin
│ └── com
│ │ └── example
│ │ └── unittesting
│ │ ├── BasePresenterTest.kt
│ │ └── login
│ │ ├── model
│ │ ├── LoginRepositoryTest.kt
│ │ └── LoginValidatorTest.kt
│ │ └── presenter
│ │ └── LoginPresenterTest.kt
│ └── resources
│ └── mockito-extensions
│ └── org.mockito.plugins.MockMaker
├── assets
├── ide_failure.png
├── ide_success.png
├── login_empty.png
├── login_validation.png
├── mock.png
├── state.png
└── stub_mock.png
├── buddybuild_postbuild.sh
├── build.gradle
├── circle.yml
├── codecov.yml
├── docs
├── Clean-Architecture.md
├── Unit-Testing-Introduction.md
├── Unit-Testing-Mockito.md
├── _config.yml
└── pt_BR
│ └── Unit-Testing-Introduction.md
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitattributes:
--------------------------------------------------------------------------------
1 | app/src/main/** linguist-vendored
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/LICENSE_HEADER:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2016 Dariusz Bacinski
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Android Testing With Kotlin
2 |
3 |
4 |
5 | This project serves as an example for set of articles about testing:
6 |
7 | #### 1. [Introduction to Unit Testing with Kotlin](/docs/Unit-Testing-Introduction.md)
8 |
9 | #### 2. [Unit Testing with Mockito 2](/docs/Unit-Testing-Mockito.md)
10 |
11 | #### 3. [Migration of Android application from Java to Kotlin](https://github.com/dbacinski/Android-Testing-With-Kotlin/pull/9)
12 |
13 |
14 | [](https://circleci.com/gh/dbacinski/Android-Testing-With-Kotlin) [](https://codecov.io/gh/dbacinski/Android-Testing-With-Kotlin)
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 | apply plugin: 'kotlin-android'
3 | apply plugin: 'jacoco-android'
4 |
5 | android {
6 | compileSdkVersion 27
7 | buildToolsVersion '26.0.2'
8 |
9 | defaultConfig {
10 | applicationId "com.example.unittesting"
11 | minSdkVersion 21
12 | targetSdkVersion 27
13 | versionCode 2
14 | versionName "1.1"
15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
16 | }
17 |
18 | buildTypes {
19 | release {
20 | minifyEnabled true
21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 |
25 | sourceSets {
26 | main.java.srcDirs += 'src/main/kotlin'
27 | test.java.srcDirs += 'src/test/kotlin'
28 | }
29 |
30 | compileOptions {
31 | sourceCompatibility JavaVersion.VERSION_1_8
32 | targetCompatibility JavaVersion.VERSION_1_8
33 | }
34 | }
35 |
36 | jacocoAndroidUnitTestReport {
37 | excludes += ['**/com/example/unittesting/login/view/**']
38 | }
39 |
40 | dependencies {
41 | compile 'com.android.support:appcompat-v7:27.0.0'
42 | compile 'com.android.support:design:27.0.0'
43 | compile 'io.reactivex.rxjava2:rxjava:2.0.8'
44 | compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
45 | compile 'com.jakewharton.timber:timber:4.3.0'
46 | compile 'com.jakewharton:butterknife:8.4.0'
47 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
48 | kapt 'com.jakewharton:butterknife-compiler:8.4.0'
49 |
50 | testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
51 | testCompile 'junit:junit:4.12'
52 | testCompile 'org.mockito:mockito-core:2.10.0'
53 | testCompile 'org.assertj:assertj-core:3.8.0'
54 | testCompile "com.nhaarman:mockito-kotlin-kt1.1:1.5.0"
55 |
56 | androidTestCompile 'com.android.support.test:runner:1.0.1'
57 | androidTestCompile 'com.android.support.test:rules:1.0.1'
58 | androidTestCompile 'com.android.support:support-annotations:27.0.0'
59 | androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2', {
60 | exclude group: 'com.android.support', module: 'support-annotations'
61 | }
62 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /Users/dariusz.bacinski/Library/Android/sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
11 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/BasePresenter.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting
2 |
3 | import io.reactivex.disposables.CompositeDisposable
4 | import io.reactivex.disposables.Disposable
5 |
6 | open class BasePresenter : Presenter {
7 |
8 | var view: T? = null
9 | private val compositeDisposable = CompositeDisposable()
10 |
11 | override fun createView(view: T) {
12 | this.view = view
13 | }
14 |
15 | fun bindToLifecycle(disposable: Disposable) {
16 | compositeDisposable.add(disposable)
17 | }
18 |
19 | override fun destroyView() {
20 | compositeDisposable.clear()
21 | view = null
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/Presenter.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting
2 |
3 | internal interface Presenter {
4 |
5 | fun createView(view: T)
6 |
7 | fun destroyView()
8 | }
9 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/ResourceProvider.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting
2 |
3 | import android.content.res.Resources
4 | import android.support.annotation.StringRes
5 |
6 | class ResourceProvider(private var resources: Resources) {
7 |
8 | fun getString(@StringRes stringResId: Int): String {
9 | return resources.getString(stringResId)
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/SchedulersFactory.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting
2 |
3 | import io.reactivex.Observable
4 | import io.reactivex.ObservableSource
5 | import io.reactivex.ObservableTransformer
6 | import io.reactivex.android.schedulers.AndroidSchedulers
7 |
8 | class SchedulersFactory {
9 |
10 | fun createMainThreadSchedulerTransformer(): ObservableTransformer {
11 | return SchedulersTransformer()
12 | }
13 | }
14 |
15 | internal class SchedulersTransformer : ObservableTransformer {
16 |
17 | override fun apply(upstream: Observable): ObservableSource {
18 | return upstream.observeOn(AndroidSchedulers.mainThread())
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/model/LoginCredentials.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.model
2 |
3 | data class LoginCredentials(val login: String, val password: String)
4 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/model/LoginRepository.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.model
2 |
3 | import io.reactivex.Observable
4 | import io.reactivex.Observable.fromCallable
5 | import timber.log.Timber
6 | import java.util.concurrent.TimeUnit
7 |
8 | class LoginRepository {
9 |
10 | fun login(login: String, password: String): Observable {
11 | Timber.v("login %s with password %s", login, password)
12 |
13 | return fromCallable { CORRECT_LOGIN == login && CORRECT_PASSWORD == password }
14 | .delay(2000, TimeUnit.MILLISECONDS)
15 | }
16 |
17 | companion object {
18 | internal val CORRECT_LOGIN = "dbacinski"
19 | internal val CORRECT_PASSWORD = "correct"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/model/LoginUseCase.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.model
2 |
3 | import io.reactivex.Observable
4 |
5 | class LoginUseCase(private val loginRepository: LoginRepository) {
6 |
7 | fun loginWithCredentialsWithStatus(credentials: LoginCredentials): Observable {
8 | return loginRepository.login(credentials.login, credentials.password)
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/model/LoginValidator.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.model
2 |
3 | class LoginValidator {
4 |
5 | companion object {
6 | val EMPTY = ""
7 | val MIN_PASSWORD_LENGTH = 6
8 | }
9 |
10 | fun validateLogin(login: String): Boolean {
11 | return login != EMPTY
12 | }
13 |
14 | fun validatePassword(password: String): Boolean {
15 | return password.length >= MIN_PASSWORD_LENGTH
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/presenter/LoginPresenter.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.presenter
2 |
3 | import com.example.unittesting.BasePresenter
4 | import com.example.unittesting.R
5 | import com.example.unittesting.ResourceProvider
6 | import com.example.unittesting.SchedulersFactory
7 | import com.example.unittesting.login.model.LoginCredentials
8 | import com.example.unittesting.login.model.LoginUseCase
9 | import com.example.unittesting.login.model.LoginValidator
10 |
11 | class LoginPresenter(private val resourceProvider: ResourceProvider, private val loginValidator: LoginValidator, private val loginUseCase: LoginUseCase, private val schedulersFactory: SchedulersFactory) : BasePresenter() {
12 |
13 | fun attemptLogin(loginCredentials: LoginCredentials) {
14 | if (!validateInputs(loginCredentials)) {
15 | return
16 | }
17 |
18 | view?.showProgress()
19 | loginUseCase.loginWithCredentialsWithStatus(loginCredentials)
20 | .compose(schedulersFactory.createMainThreadSchedulerTransformer())
21 | .subscribe { success ->
22 | view?.hideProgress()
23 |
24 | if (success) {
25 | view?.onLoginSuccessful()
26 | } else {
27 | view?.showPasswordError(resourceProvider.getString(R.string.error_incorrect_password))
28 | view?.requestPasswordFocus()
29 | }
30 | }
31 | }
32 |
33 | private fun validateInputs(loginCredentials: LoginCredentials): Boolean {
34 | val validateLogin = validateLogin(loginCredentials)
35 | return validatePassword(loginCredentials) && validateLogin //XXX validateLogin is not inlined to avoid short circuit check
36 | }
37 |
38 | private fun validateLogin(loginCredentials: LoginCredentials): Boolean =
39 | if (loginValidator.validateLogin(loginCredentials.login)) {
40 | view?.showLoginError(null)
41 | true
42 | } else {
43 | view?.showLoginError(resourceProvider.getString(R.string.error_field_required))
44 | view?.requestLoginFocus()
45 | false
46 | }
47 |
48 | private fun validatePassword(loginCredentials: LoginCredentials): Boolean =
49 | if (loginValidator.validatePassword(loginCredentials.password)) {
50 | view?.showPasswordError(null)
51 | true
52 | } else {
53 | view?.showPasswordError(resourceProvider.getString(R.string.error_invalid_password))
54 | view?.requestPasswordFocus()
55 | false
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/presenter/LoginView.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.presenter
2 |
3 | interface LoginView {
4 |
5 | fun showProgress()
6 |
7 | fun hideProgress()
8 |
9 | fun onLoginSuccessful()
10 |
11 | fun showLoginError(errorMessage: String?)
12 |
13 | fun showPasswordError(errorMessage: String?)
14 |
15 | fun requestLoginFocus()
16 |
17 | fun requestPasswordFocus()
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/kotlin/com/example/unittesting/login/view/LoginActivity.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.view
2 |
3 | import android.os.Bundle
4 | import android.support.v7.app.AppCompatActivity
5 | import android.view.View
6 | import android.widget.EditText
7 | import butterknife.BindView
8 | import butterknife.ButterKnife
9 | import butterknife.OnClick
10 | import com.example.unittesting.R
11 | import com.example.unittesting.ResourceProvider
12 | import com.example.unittesting.SchedulersFactory
13 | import com.example.unittesting.login.model.LoginCredentials
14 | import com.example.unittesting.login.model.LoginRepository
15 | import com.example.unittesting.login.model.LoginUseCase
16 | import com.example.unittesting.login.model.LoginValidator
17 | import com.example.unittesting.login.presenter.LoginPresenter
18 | import com.example.unittesting.login.presenter.LoginView
19 |
20 | /**
21 | * Based on Google Login Screen example
22 | */
23 | class LoginActivity : AppCompatActivity(), LoginView {
24 |
25 | @BindView(R.id.email)
26 | lateinit var loginView: EditText
27 | @BindView(R.id.password)
28 | lateinit var passwordView: EditText
29 | @BindView(R.id.login_progress)
30 | lateinit var progressView: View
31 | @BindView(R.id.login_form)
32 | lateinit var loginFormView: View
33 |
34 | //TODO @Inject
35 | lateinit var loginPresenter: LoginPresenter
36 |
37 | override fun onCreate(savedInstanceState: Bundle?) {
38 | super.onCreate(savedInstanceState)
39 | setContentView(R.layout.activity_login)
40 |
41 | ButterKnife.bind(this)
42 |
43 | passwordView.setOnEditorActionListener { _, id, _ ->
44 | if (id == 1) {
45 | onSignInClick()
46 | true
47 | } else {
48 | false
49 | }
50 | }
51 |
52 | loginPresenter = LoginPresenter(ResourceProvider(resources), LoginValidator(), LoginUseCase(LoginRepository()), SchedulersFactory())
53 | loginPresenter.createView(this)
54 | }
55 |
56 | override fun onDestroy() {
57 | loginPresenter.destroyView()
58 | super.onDestroy()
59 | }
60 |
61 | @OnClick(R.id.email_sign_in_button)
62 | fun onSignInClick() {
63 | loginPresenter.attemptLogin(
64 | LoginCredentials(
65 | login = loginView.text.toString(),
66 | password = passwordView.text.toString()
67 | )
68 | )
69 | }
70 |
71 | override fun showProgress() {
72 | showProgress(true)
73 | }
74 |
75 | override fun hideProgress() {
76 | showProgress(false)
77 | }
78 |
79 | override fun onLoginSuccessful() {
80 | finish()
81 | }
82 |
83 | override fun showLoginError(errorMessage: String?) {
84 | loginView.error = errorMessage
85 | }
86 |
87 | override fun showPasswordError(errorMessage: String?) {
88 | passwordView.error = errorMessage
89 | }
90 |
91 | override fun requestLoginFocus() {
92 | loginView.requestFocus()
93 | }
94 |
95 | override fun requestPasswordFocus() {
96 | passwordView.requestFocus()
97 | }
98 |
99 | internal fun showProgress(progressVisible: Boolean) {
100 | val animationDuration = resources.getInteger(android.R.integer.config_shortAnimTime)
101 |
102 | loginFormView.visibility = if (progressVisible) View.GONE else View.VISIBLE
103 | loginFormView.animate().setDuration(animationDuration.toLong()).alpha((if (progressVisible) 0 else 1).toFloat())
104 |
105 | progressView.visibility = if (progressVisible) View.VISIBLE else View.GONE
106 | progressView.animate().setDuration(animationDuration.toLong()).alpha((if (progressVisible) 1 else 0).toFloat())
107 | }
108 | }
109 |
110 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_login.xml:
--------------------------------------------------------------------------------
1 |
12 |
13 |
20 |
21 |
25 |
26 |
31 |
32 |
35 |
36 |
43 |
44 |
45 |
46 |
49 |
50 |
60 |
61 |
62 |
63 |
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #4E62C6
4 | #414EAF
5 | #FF5193
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Kotlin Unit Testing
3 |
4 |
5 | Login
6 | Password
7 | Sign in
8 | Sign in
9 | This email address is invalid
10 | This password is too short
11 | This password is incorrect
12 | This field is required
13 |
14 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/example/unittesting/BasePresenterTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting
2 |
3 | import io.reactivex.Observable
4 | import org.assertj.core.api.Assertions.assertThat
5 | import org.junit.Test
6 | import java.util.concurrent.TimeUnit
7 |
8 | class BasePresenterTest {
9 |
10 | val objectUnderTest = BasePresenter()
11 |
12 | @Test
13 | fun `dispose observables on destroy view`() {
14 | //given
15 | val disposable = Observable.interval(100, TimeUnit.MILLISECONDS).subscribe()
16 | objectUnderTest.bindToLifecycle(disposable)
17 | //when
18 | objectUnderTest.destroyView()
19 | //then
20 | assertThat(disposable.isDisposed).isTrue()
21 | }
22 |
23 | @Test
24 | fun `clean view reference on destroy view`() {
25 | //given
26 | objectUnderTest.createView(TestView())
27 | //when
28 | objectUnderTest.destroyView()
29 | //then
30 | assertThat(objectUnderTest.view).isNull()
31 | }
32 | }
33 |
34 | class TestView {
35 |
36 | }
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/example/unittesting/login/model/LoginRepositoryTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.model
2 |
3 | import com.example.unittesting.login.model.LoginRepository.Companion.CORRECT_LOGIN
4 | import com.example.unittesting.login.model.LoginRepository.Companion.CORRECT_PASSWORD
5 | import org.junit.Test
6 |
7 | class LoginRepositoryTest {
8 |
9 | val objectUnderTest = LoginRepository()
10 |
11 | @Test
12 | fun `login with correct login and password`() {
13 | //given
14 | val login = CORRECT_LOGIN
15 | val password = CORRECT_PASSWORD
16 | //when
17 | val result = objectUnderTest.login(login, password)
18 | //then
19 | result.test().await()
20 | .assertResult(true)
21 | }
22 |
23 | @Test
24 | fun `do not login with only correct login`() {
25 | //given
26 | val login = CORRECT_LOGIN
27 | val password = "anyPassword"
28 | //when
29 | val result = objectUnderTest.login(login, password)
30 | //then
31 | result.test().await()
32 | .assertResult(false)
33 | }
34 |
35 | @Test
36 | fun `do not login with only correct password`() {
37 | //given
38 | val login = "anyLogin"
39 | val password = CORRECT_PASSWORD
40 | //when
41 | val result = objectUnderTest.login(login, password)
42 | //then
43 | result.test().await()
44 | .assertResult(false)
45 | }
46 | }
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/example/unittesting/login/model/LoginValidatorTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.model
2 |
3 | import org.assertj.core.api.Assertions.assertThat
4 | import org.junit.Test
5 |
6 | class LoginValidatorTest {
7 |
8 | val objectUnderTest = LoginValidator()
9 |
10 | @Test
11 | fun `empty login is invalid`() {
12 | //when
13 | val result = objectUnderTest.validateLogin("")
14 | //then
15 | assertThat(result).isFalse()
16 | }
17 |
18 | @Test
19 | fun `not empty login is valid`() {
20 | //when
21 | val result = objectUnderTest.validateLogin("anyLogin")
22 | //then
23 | assertThat(result).isTrue()
24 | }
25 |
26 | @Test
27 | fun `empty password is invalid`() {
28 | //when
29 | val result = objectUnderTest.validatePassword("")
30 | //then
31 | assertThat(result).isFalse()
32 | }
33 |
34 | @Test
35 | fun `password is invalid if shorter then limit`() {
36 | //when
37 | val result = objectUnderTest.validatePassword("12345")
38 | //then
39 | assertThat(result).isFalse()
40 | }
41 |
42 | @Test
43 | fun `password is valid if equal to limit`() {
44 | //when
45 | val result = objectUnderTest.validatePassword("123456")
46 | //then
47 | assertThat(result).isTrue()
48 | }
49 |
50 | @Test
51 | fun `password is valid if longer than limit`() {
52 | //when
53 | val result = objectUnderTest.validatePassword("1234567")
54 | //then
55 | assertThat(result).isTrue()
56 | }
57 | }
--------------------------------------------------------------------------------
/app/src/test/kotlin/com/example/unittesting/login/presenter/LoginPresenterTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.unittesting.login.presenter
2 |
3 | import android.content.res.Resources
4 | import com.example.unittesting.ResourceProvider
5 | import com.example.unittesting.SchedulersFactory
6 | import com.example.unittesting.login.model.LoginCredentials
7 | import com.example.unittesting.login.model.LoginRepository
8 | import com.example.unittesting.login.model.LoginUseCase
9 | import com.example.unittesting.login.model.LoginValidator
10 | import com.nhaarman.mockito_kotlin.any
11 | import io.reactivex.Observable
12 | import io.reactivex.ObservableTransformer
13 | import org.junit.Before
14 | import org.junit.Test
15 | import org.mockito.ArgumentMatchers.anyInt
16 | import org.mockito.BDDMockito.given
17 | import org.mockito.Mockito.*
18 |
19 | class LoginPresenterTest {
20 |
21 | val loginViewMock: LoginView = mock(LoginView::class.java)
22 | val resourcesStub: Resources = mock(Resources::class.java)
23 | val schedulersFactoryStub: SchedulersFactory = mock(SchedulersFactory::class.java)
24 | val loginRepositoryStub = mock(LoginRepository::class.java)
25 |
26 | val objectUnderTest = LoginPresenter(ResourceProvider(resourcesStub), LoginValidator(), LoginUseCase(loginRepositoryStub), schedulersFactoryStub)
27 |
28 | @Before
29 | fun setUp() {
30 | removeObserveOnMainThreadScheduler()
31 | objectUnderTest.createView(loginViewMock)
32 | }
33 |
34 | @Test
35 | fun `login with correct data`() {
36 | //given
37 | given(loginRepositoryStub.login(any(), any())).willReturn(Observable.just(true))
38 | //when
39 | objectUnderTest.attemptLogin(LoginCredentials(login = "correct", password = "correct"))
40 | //then
41 | verify(loginViewMock).onLoginSuccessful()
42 | }
43 |
44 | @Test
45 | fun `login with correct data with progress indication`() {
46 | //given
47 | given(loginRepositoryStub.login(any(), any())).willReturn(Observable.just(true))
48 | //when
49 | objectUnderTest.attemptLogin(LoginCredentials(login = "correct", password = "correct"))
50 | //then
51 | val ordered = inOrder(loginViewMock)
52 | ordered.verify(loginViewMock).showProgress()
53 | ordered.verify(loginViewMock).hideProgress()
54 | }
55 |
56 | @Test
57 | fun `login with valid but incorrect data`() {
58 | //given
59 | given(resourcesStub.getString(anyInt())).willReturn("error")
60 | given(loginRepositoryStub.login(any(), any())).willReturn(Observable.just(false))
61 | //when
62 | objectUnderTest.attemptLogin(LoginCredentials(login = "valid", password = "incorrectPassword"))
63 | //then
64 | val ordered = inOrder(loginViewMock)
65 | ordered.verify(loginViewMock).showLoginError(null)
66 | ordered.verify(loginViewMock).showPasswordError("error")
67 | }
68 |
69 | @Test
70 | fun `show validation error for empty email`() {
71 | //given
72 | given(resourcesStub.getString(anyInt())).willReturn("error")
73 | val login = ""
74 | //when
75 | objectUnderTest.attemptLogin(LoginCredentials(login = login, password = "validPassword"))
76 | //then
77 | verify(loginViewMock).showLoginError("error")
78 | verify(loginViewMock).showPasswordError(null)
79 | }
80 |
81 | @Test
82 | fun `show validation error for empty email and too short password`() {
83 | //given
84 | given(resourcesStub.getString(anyInt())).willReturn("error")
85 | val login = ""
86 | val password = "short"
87 | //when
88 | objectUnderTest.attemptLogin(LoginCredentials(login = login, password = password))
89 | //then
90 | verify(loginViewMock).showLoginError("error")
91 | verify(loginViewMock).showPasswordError("error")
92 | }
93 |
94 | @Test
95 | fun `show validation error for too short password`() {
96 | //given
97 | given(resourcesStub.getString(anyInt())).willReturn("error")
98 | val password = "short"
99 | //when
100 | objectUnderTest.attemptLogin(LoginCredentials(login = "valid", password = password))
101 | //then
102 | verify(loginViewMock).showLoginError(null)
103 | verify(loginViewMock).showPasswordError("error")
104 | }
105 |
106 | private fun removeObserveOnMainThreadScheduler() {
107 | given(schedulersFactoryStub.createMainThreadSchedulerTransformer()).willReturn(ObservableTransformer { it })
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker:
--------------------------------------------------------------------------------
1 | mock-maker-inline
--------------------------------------------------------------------------------
/assets/ide_failure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/ide_failure.png
--------------------------------------------------------------------------------
/assets/ide_success.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/ide_success.png
--------------------------------------------------------------------------------
/assets/login_empty.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/login_empty.png
--------------------------------------------------------------------------------
/assets/login_validation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/login_validation.png
--------------------------------------------------------------------------------
/assets/mock.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/mock.png
--------------------------------------------------------------------------------
/assets/state.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/state.png
--------------------------------------------------------------------------------
/assets/stub_mock.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/assets/stub_mock.png
--------------------------------------------------------------------------------
/buddybuild_postbuild.sh:
--------------------------------------------------------------------------------
1 | ./gradlew jacocoTestReport
2 | bash <(curl -s https://codecov.io/bash)
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | ext.kotlin_version = '1.1.51'
3 | repositories {
4 | maven { url 'https://maven.google.com' }
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:3.0.0'
9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
10 | classpath 'com.dicedmelon.gradle:jacoco-android:0.1.1'
11 | }
12 | }
13 |
14 | allprojects {
15 | repositories {
16 | maven { url 'https://maven.google.com' }
17 | jcenter()
18 | }
19 | }
20 |
21 | task clean(type: Delete) {
22 | delete rootProject.buildDir
23 | }
24 |
--------------------------------------------------------------------------------
/circle.yml:
--------------------------------------------------------------------------------
1 | dependencies:
2 | pre:
3 | - echo y | android update sdk --no-ui --all --filter "android-27,build-tools-26.0.2"
4 | - chmod +x gradlew
5 | test:
6 | override:
7 | - ./gradlew build test
8 | - cp ./*/build/outputs/apk/release/*.apk $CIRCLE_ARTIFACTS/
9 | - cp ./*/build/test-results/testDebugUnitTest/*.xml $CIRCLE_TEST_REPORTS/
10 | post:
11 | - bash <(curl -s https://codecov.io/bash)
12 |
--------------------------------------------------------------------------------
/codecov.yml:
--------------------------------------------------------------------------------
1 | codecov:
2 | token: 8b7ff9b0-a9bb-40bc-9595-417b22930ca4
--------------------------------------------------------------------------------
/docs/Clean-Architecture.md:
--------------------------------------------------------------------------------
1 | ## 1. Clean Architecture with Model View Presenter [Work in Progress]
2 |
3 | ### 1.1 Model
4 |
5 | #### 1.1.1 Entity
6 | - Contains implementation of Business Rules
7 | - Should not contain platform or application specific implementation
8 | - It is least like to change when something external changes
9 |
10 | #### 1.1.2 Domain
11 |
12 | ### 1.2 Presenter
13 |
14 | ### 1.3 View
15 |
16 | ## 2. Testing
17 |
--------------------------------------------------------------------------------
/docs/Unit-Testing-Introduction.md:
--------------------------------------------------------------------------------
1 | #### Translations
2 | - [Portuguese](/docs/pt_BR/Unit-Testing-Introduction.md)
3 |
4 | # Introduction to Unit Testing with Kotlin
5 |
6 | Have you ever heard good stuff about unit testing and finally you want to learn about it? This is a place for you!
7 |
8 | Join me and I will guide you through basic theory of unit testing. I assume that you are a developer who knows how to create Android applications but does not have any experience with automatic testing.
9 |
10 | ## What is a Unit Test
11 |
12 | So let’s start with very basic things. What is a Unit Test actually?
13 |
14 | Unit Test is a piece of code that is not a part of your application. It can create and call all of your application’s public classes and methods. But why would you like to write a code that won't be a part of your application? Simply because you want to verify whether application code works as you expect. And you want to verify it over and over again to be sure that you do not break any existing functionalities. And you are probably lazy like me and do not want to do it manually! So you can write test code that will verify application behavior for you. Unit Tests for the rescue!
15 |
16 | But wait a second! You probably heard about UI and Integration Tests which do exactly the same thing. What differentiates Unit Tests from the other tests?
17 |
18 | Unit Test is focused on testing only set of classes (one or more) that fulfils single functionality (domain) and do not depend on libraries or framework code. You do not want to test libraries that you are using (at least not in an Unit Test), they should just work! You want to focus only on your precious code and prove yourself that there are no hidden bugs.
19 |
20 | If you want to read more about test types you can read [this article](https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html), but now let’s move on.
21 |
22 | ### Simple Android application
23 |
24 | Before creating any test I want to introduce you to a simple Android app that provides a login screen. It has two inputs for login and password, and it validates those inputs. When the inputs are valid we can sign in with correct data or get an error that credentials are incorrect. I have chosen MVP architecture, which will help us to write tests that do not depend on Android framework. If you are not familiar with this architecture then please read [this article](http://macoscope.com/blog/model-view-presenter-architecture-in-android-applications/).
25 |
26 |
27 |
28 |
29 |
30 | ## Project setup
31 |
32 | Now when we have an application to be tested we can create our first test. We will use [JUnit4](https://github.com/junit-team/junit4/wiki/getting-started) test runner and Kotlin programming language. Test runner is a library that runs our test code and aggregates results in a friendly way. I won't go into details how to setup Android project with tests written in Kotlin, because there is a great [article](http://fernandocejas.com/2017/02/03/android-testing-with-kotlin/) that describes it in details. You can also check [Android-Testing-In-Kotlin project](/app/build.gradle) setup.
33 |
34 | ## Your first test
35 |
36 | To create our first test we have to create a class with public method annotated with `@org.junit.Test` in `/src/test/kotlin` folder. This way we tell JUnit4 where the test code is located. We can start with checking whether our app allows us to login with correct data. We want to instrument [LoginRepository](/app/src/main/kotlin/com/example/unittesting/login/presenter/LoginPresenter.kt), to do that I have to create [LoginRepositoryTest](/app/src/test/kotlin/com/example/unittesting/login/presenter/LoginPresenterTest.kt) class with test method. At the beginning we want to test if it is possible to sign in with correct credentials, so I have created test method with name `login with correct login and password`.
37 |
38 | ``` kotlin
39 | class LoginRepositoryTest {
40 |
41 | @Test
42 | fun `login with correct login and password`() {
43 |
44 | }
45 | }
46 | ```
47 | In Kotlin we can name test with natural names like `login with correct login and password` but it only applies to code which is ran on JVM. Thankfully unit tests are ran on JVM and we can use such descriptive names.
48 |
49 | > Tip: To suppress error `Identifier not allowed for Android project...` displayed by Android Studio you have to go to `Preferences... -> Editor -> Inspections -> Kotlin` and find `Illegal Android Identifier` inspection and then select `Tests` in `In All Scopes` to disable the check for the tests.
50 |
51 | ## Test structure
52 |
53 | Each test should be created from the following blocks:
54 |
55 | - Arrange/Given - in which we will prepare all needed data required to perform test
56 | - Act/When - in which we will call single method on tested object
57 | - Assert/Then - in which we will check result of the test, either pass or fail
58 |
59 | JUnit4 does not separate test blocks in any way, so it is convenient to add comments to a test code. Especially, if you are just beginning your journey with tests.
60 |
61 | ``` kotlin
62 | @Test
63 | fun `login with correct login and password`() {
64 | //given
65 |
66 | //when
67 |
68 | //then
69 |
70 | }
71 | ```
72 | ## Given Block
73 |
74 | Our test begins with `given` block in which we will prepare our test data and create tested object.
75 |
76 | I am [creating instance](https://kotlinlang.org/docs/reference/classes.html#creating-instances-of-classes) of tested object `LoginRepository` and assign it to [read-only property](https://kotlinlang.org/docs/reference/properties.html#declaring-properties). It is very convenient to distinguish tested object from test parameters, so I am calling it `objectUnderTest`. You can also name it: `sut`, `subject` or `target`. Choose the name which fits you best just be consistent across your project.
77 |
78 | When we have instance of tested object, then we can move on to test parameters. That will be `correctLogin` with value `'dbacinski'` and `correctPassword` with value `'correct'`. It is very important to choose meaningful names for each test parameter, it must be clear what kind of values each of them contain.
79 |
80 | ``` kotlin
81 | @Test
82 | fun `login with correct login and password`() {
83 | //given
84 | val objectUnderTest = LoginRepository()
85 | val correctLogin = 'dbacinski'
86 | val correctPassword = `correct`
87 | //when
88 |
89 | //then
90 |
91 | }
92 | ```
93 |
94 | Now `given` block is finished and we can move on.
95 |
96 | ## When Block
97 |
98 | In `when` block we have to call method that we want to test with parameters that were prepared in the `given` block. So I call method `objectUnderTest.login(correctLogin, correctPassword)`. In `when` block we should have only one line of code to make it clear what is actually being tested.
99 |
100 |
101 | ``` kotlin
102 | @Test
103 | fun `login with correct login and password`() {
104 | //given
105 | val objectUnderTest = LoginRepository()
106 | val correctLogin = 'dbacinski'
107 | val correctPassword = `correct`
108 | //when
109 | objectUnderTest.login(correctLogin, correctPassword)
110 | //then
111 |
112 | }
113 | ```
114 |
115 | ## Then Block
116 |
117 | It is time to verify if tested object return value that we expect. But first we have to store result of tested method in a property `val result` and then examine it in the `then` block. Now we can do an assertion which checks if result value is the value that we expect. It will throw an error when assertion won’t be satisfied and test will fail.
118 |
119 | In this case returned object is RxJava 2 Observable but we can convert it easily to `TestObserver` which is a class that provides assertion methods. I am checking if result value is `true` otherwise test will fail.
120 |
121 | Testing RxJava Observables is a topic for a separate article and I won’t go into more details here.
122 |
123 | ``` kotlin
124 | @Test
125 | fun `login with correct login and password`() {
126 | //given
127 | val objectUnderTest = LoginRepository()
128 | val correctLogin = 'dbacinski'
129 | val correctPassword = `correct`
130 | //when
131 | val result = objectUnderTest.login(login, password)
132 | //then
133 | result.test().assertResult(true)
134 | }
135 | ```
136 | ## Running test
137 |
138 | We can run a test by pressing `Ctrl + Shift + F10` in Android Studio/IntelliJ or from a Terminal using command `./gradlew test`.
139 |
140 | After running test that we have just written, you should get a green bar in IDE or `BUILD SUCCESSFUL` output in the Terminal.
141 |
142 |
143 |
144 |
145 |
146 | ## Test failure
147 |
148 | When the assertion from `then` block won't be satisfied then test will fail with the following output:
149 |
150 |
151 |
152 |
153 |
154 | We have an information that expected value should be `true` but actual value returned by tested object was `false`.
155 |
156 | ``` java
157 | java.lang.AssertionError:
158 | Values at position 0 differ; Expected: true (class: Boolean),
159 | Actual: false (class: Boolean) (latch = 0, values = 1, errors = 0, completions = 1)
160 | ```
161 |
162 | We also can see that failed test has the name `login with correct login and password` and is in the class `LoginRepositoryTest`. Assertion has failed at line `20` in file `LoginRepositoryTest.kt`. Thanks to such an informative error message, we can figure out exactly which assertion was not satisfied and fix the tested object.
163 |
164 | ``` java
165 | at com.example.unittesting.entity.login.LoginRepositoryTest
166 | .login with correct login and password(LoginRepositoryTest.kt:20)
167 | ```
168 |
169 | ## Conclusion
170 |
171 | At this point you are ready to write your first very basic unit test, run it and examine what went wrong when it failed. Stay tuned for next more advanced topics. If you have found some errors feel free to create a Pull Request. You can also propose next testing related topic by creating an [Issue](https://github.com/dbacinski/Android-Testing-With-Kotlin/issues/new).
172 |
173 | If you like my article, please don’t forget to [give a :star:](https://github.com/dbacinski/Android-Testing-With-Kotlin/).
174 |
175 |
176 | #### Next: [Unit Testing with Mockito 2](/docs/Unit-Testing-Mockito.md)
177 |
--------------------------------------------------------------------------------
/docs/Unit-Testing-Mockito.md:
--------------------------------------------------------------------------------
1 | # Unit Testing with Mockito 2
2 |
3 | #### Previous: [Introduction to Unit Testing with Kotlin](/docs/Unit-Testing-Introduction.md)
4 |
5 | In the [previous article](/docs/Unit-Testing-Introduction.md) you have learned how to write a simple unit test. Now it is a time to dive deeper and learn about testing state and interactions with help of testing library Mockito 2.
6 |
7 | At the beginning a bit of theory. There are two ways how you can verify if tested object is working correctly. You can test object state or test how object interacts with it’s dependencies.
8 |
9 | ## Testing State
10 |
11 | Testing State is verifying that the object under test returns the right results after calling given method. In example when we want to test if [LoginValidator](/app/src/main/kotlin/com/example/unittesting/login/model/LoginValidator.kt) works correctly we can call method `validatePassword` and check if returned value is equal to what we expect. Assertion is done using [AssertJ](http://joel-costigliola.github.io/assertj/assertj-core-quick-start.html) library which provides fluent api for common `Java` objects.
12 |
13 | ```kotlin
14 | @Test
15 | fun `empty password is invalid`() {
16 | //given
17 | val objectUnderTest = LoginValidator()
18 | //when
19 | val result = objectUnderTest.validatePassword("")
20 | //then
21 | assertThat(result).isFalse()
22 | }
23 | ```
24 | While testing State we do not make any assumption on how object is implemented. We treat object as a black box and check if it returns correct values for a given input. This kind of test is most preferable because we can make changes to class implementation and test won’t fail until all our expectations are still met. Thanks to that this, tests are more stable and less painful to maintain.
25 |
26 |
27 |
28 |
29 |
30 | ## Testing Interactions
31 |
32 | Unfortunately oftentimes object do not expose almost any state but it forwards processing to it’s dependencies. This is very common case in MVP architecture in which `Presenter` do not return any values from its methods but rather invokes callbacks on a `View` interface. Take a look at [LoginPresenter](/app/src/main/kotlin/com/example/unittesting/login/presenter/LoginPresenter.kt) which exposes method `void attemptLogin(LoginCredentials loginCredentials)`. There is no return type but when we will look at its implementation then we will see that it invokes method `onLoginSuccessful()` on [LoginView](/app/src/main/kotlin/com/example/unittesting/login/presenter/LoginView.kt) only when login is successful. So the only way to check if login was successful is to check if method `onLoginSuccess()` was actually called.
33 | ```java
34 | public class LoginPresenter {
35 |
36 | private LoginView view
37 |
38 | public void createView(T view) {
39 | this.view = view;
40 | }
41 |
42 | public void attemptLogin(LoginCredentials loginCredentials) {
43 | loginUseCase.loginWithCredentialsWithStatus(loginCredentials)
44 | .subscribe(success -> {
45 | if (success) {
46 | view.onLoginSuccessful();
47 | }
48 | [...]
49 | });
50 | }
51 | }
52 | ```
53 |
54 | We can test such case by introducing test double. Test doubles are objects that replaces dependencies of object under test. They help to test object in separation from real dependencies. If you want to learn more about test doubles there is a [great article](http://pragmatists.pl/blog/2017/03/test-doubles-fakes-mocks-or-stubs/) by [Pragmatist](https://twitter.com/pragmatists) about it.
55 |
56 | To test if `LoginPresenter` calls `view.onLoginSuccessful()` method we have to introduce test double called Mock object.
57 |
58 | ### Mock
59 |
60 | Mock object provides a way to check if object under test has called certain methods. It is possible to implement Mock object by ourself but it does not make much sense because there is a great library called [Mockito](http://mockito.org) which will do it for us.
61 |
62 |
63 |
64 |
65 |
66 | First we have to create a Mock object from our dependency `LoginView`. It can be done by using `loginViewMock = Mockito.mock(LoginView::class.java)` syntax. Now we have to pass created Mock to tested object instead of a real dependency. In this case we are passing mock view by calling `createView(loginViewMock)` method.
67 |
68 | ```kotlin
69 | val loginViewMock: LoginView = mock(LoginView::class.java)
70 | val objectUnderTest = LoginPresenter()
71 |
72 |
73 | @Test
74 | fun `login with correct data`() {
75 | //given
76 | objectUnderTest.createView(loginViewMock)
77 | }
78 | ```
79 | Next we have to call tested method `attemptLogin`. To verify if `onLoginSuccessful()` was called we have to use Mockito utility called `verify`. We have to use syntax `Mockito.verify(loginViewMock).onLoginSuccessful()` to verify if `onLoginSuccessful()` was called on mock object exactly once.
80 |
81 | ```kotlin
82 | val loginViewMock: LoginView = Mockito.mock(LoginView::class.java)
83 | val objectUnderTest = LoginPresenter()
84 |
85 |
86 | @Test
87 | fun `login with correct data`() {
88 | //given
89 | val correctLogin = "dbacinski"
90 | val correctPassword = "correct"
91 | objectUnderTest.createView(loginViewMock)
92 | //when
93 | objectUnderTest.attemptLogin(LoginCredentials()
94 | .withLogin(correctLogin)
95 | .withPassword(correctPassword))
96 | //then
97 | Mockito.verify(loginViewMock).onLoginSuccessful()
98 | }
99 | ```
100 |
101 | We have tested how `LoginPresenter` is interacting with `LoginView`.
102 |
103 | When we will look again at implementation we will notice that `LoginPresenter` is also calling `LoginUseCase` which is then calling `LoginRepository` to verify if credentials are correct. The problem is that in the real application this would cause network communication and we do not want to do it in the Unit Tests. This is where we can use next test double called Stub.
104 |
105 | ### Stub
106 |
107 | Stub is a test double which returns configured values. When a given method is invoked on stub then it returns values that were predefined in test. This gives us full control over returned values from methods that were invoke on the dependency.
108 |
109 |
110 |
111 |
112 |
113 | Let’s look at `LoginUseCase`. It invokes `login` method on `LoginRepository` with two parameters. As a result we are getting `Observable` that contains an information if login was successful or not. In Unit Test we would like to have control over returned value from `login` method. To do that we have to replace real `LoginRepository` with it’s stubbed version. This is where Mockito can help us again and generate object stub.
114 |
115 | ```java
116 | public class LoginUseCase {
117 |
118 | LoginRepository loginRepository;
119 |
120 | public LoginUseCase(LoginRepository loginRepository) {
121 | this.loginRepository = loginRepository;
122 | }
123 |
124 | public Observable loginWithCredentialsWithStatus(final LoginCredentials credentials) {
125 | checkNotNull(credentials);
126 | return loginRepository.login(credentials.login, credentials.password);
127 | }
128 |
129 | [...]
130 | }
131 | ```
132 | In order to create stubbed object with Mockito we have to invoke `Mockito.mock()` method.
133 |
134 | What? You said `mock()`? Yes, the name of the method is a bit misleading, because Mockito is creating objects that can be both Stubs and Mocks using single method called `mock()`. This probably why many people confused Stubs and Mocks. You can read more about diffrences between mocks and stubs in this [article](https://martinfowler.com/articles/mocksArentStubs.html) by Martin Fowler.
135 |
136 | Getting back to the topic. We would like to force `loginRepositorStub` stub to always return `true` for any input values. To do that we have at least two options. We can use `when` syntax and do it like this `Mockito.’when’(loginRepositoryStub.login(any(), any())).thenReturn(Observable.just(true))`. The problem is that `when` is a keyword in Kotlin and we have to escape method name. Fortunately Mockito also supports [BDD](https://en.wikipedia.org/wiki/Behavior-driven_development) syntax and we can achive the same result using `given(loginRepositoryStub.login(any(), any())).willReturn(Observable.just(true))`. Now for any credentials passed to login method we always get Observable with true value.
137 |
138 | ```kotlin
139 | val loginRepositoryStub = mock(LoginRepository::class.java)
140 | val loginViewMock: LoginView = mock(LoginView::class.java)
141 |
142 | val objectUnderTest = LoginPresenter(LoginUseCase(loginRepositoryStub))
143 |
144 | @Test
145 | fun `login with correct data`() {
146 | //given
147 | objectUnderTest.createView(loginViewMock)
148 | given(loginRepositoryStub.login(any(), any())).willReturn(Observable.just(true))
149 | //when
150 | objectUnderTest.attemptLogin(LoginCredentials().withLogin("correct").withPassword("correct"))
151 | //then
152 | verify(loginViewMock).onLoginSuccessful()
153 | }
154 | ```
155 | Thanks to `loginRepositoryStub` we have full control over external dependency and we can verify how our object works when login is successful (or not). We also do not have to rely on any unpredictable and slow source like backend API. This makes our test rock solid and lightning fast. Stubs are also very useful while testing state so do not be afraid to mix and match testing state and interactions.
156 |
157 | ## Conclusion
158 |
159 | In this article you have learned basics how to use Mockito to test your objects. Always try to favor testing state over interactions, because it makes your tests much more stable and less sensitive to refactorings. Make use of Stubs to control dependencies and speed up your tests. Try to avoid Mocks where it is possible to test the same thing by checking object state. Use also AssertJ to make your assertions more readable. Stay tuned for next more advanced topics. If you have found some errors feel free to create a Pull Request. You can also propose next testing related topic by creating an [Issue](https://github.com/dbacinski/Android-Testing-With-Kotlin/issues/new).
160 |
161 |
162 | If you like my article, please don’t forget to [give a :star:](https://github.com/dbacinski/Android-Testing-With-Kotlin/).
163 |
--------------------------------------------------------------------------------
/docs/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-slate
--------------------------------------------------------------------------------
/docs/pt_BR/Unit-Testing-Introduction.md:
--------------------------------------------------------------------------------
1 | ### Traduzido por:
2 | - Lucas Soares Candalo (@candalo)
3 |
4 | # Introdução à Testes Unitários com Kotlin
5 |
6 | Você já ouviu boas coisas sobre testes unitários e deseja finalmente aprender sobre eles? Esse é o lugar pra você!
7 |
8 | Junte-se à mim e eu irei guiá-lo através da teoria básica dos testes unitários. Eu assumo que você é um desenvolvedor que sabe como criar aplicativos Android mas não tem nenhuma experiência com testes unitários.
9 |
10 | ## O que é um Teste Unitário
11 |
12 | Vamos começar com coisas bem básicas. O que é realmente um Teste Unitário?
13 |
14 | Teste Unitário é um pedaço de código que não faz parte da sua aplicação. Ele pode criar e chamar todas as classes e métodos públicos da sua aplicação. Mas por que você iria querer escrever um código que não faça parte da sua aplicação? Apenas porque você deseja verificar se o código da aplicação funciona como o esperado. E você também sempre precisa confirmar isso para ter certeza que você não quebrou nenhuma funcionalidade existente. E você é provavelmente preguiçoso como eu e não deseja fazer isso manualmente! Então você pode escrever códigos de teste que irão verificar o comportamento da aplicação para você. Testes Unitários para o resgate!
15 |
16 | Mas espere um segundo! Você provavelmente já ouviu falar sobre Testes de Integração e Testes de UI que fazem exatamente a mesma coisa. O que diferencia Testes Unitários dos outros testes?
17 |
18 | Teste Unitário é focado em testar apenas conjunto de classes (uma ou mais) que atende uma única funcionalidade (domínio) e não depende do código de bibliotecas ou frameworks. Você não deseja testar as bibliotecas que você está usando (pelo menos não no Teste Unitário), eles devem apenas funcionar! Você tem que se focar apenas no seu precioso código e provar para si mesmo que não existem bugs escondidos.
19 |
20 | Se você deseja ler mais sobre os diferentes tipos de teste, você pode ler [esse artigo (em inglês)](https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html), mas agora vamos prosseguir.
21 |
22 | ### Uma aplicação Android simples
23 | Antes de criar qualquer teste eu quero introduzir você à um aplicativo Android simples que fornece uma tela de login. Essa tela tem duas entradas para login e senha, e ela valida essas entradas. Quando as entradas são válidas nós podemos logar com os dados corretos ou receber um error indicando que as credenciais estão incorretas. Eu escolhi a arquitetura MVP, que irá nos ajudar a escrever testes que não dependam do framework do Android. Se você não é familiar com essa arquitetura, por favor leia [esse artigo (em inglês)](http://macoscope.com/blog/model-view-presenter-architecture-in-android-applications/).
24 |
25 |
26 |
27 |
28 |
29 | ## Setup do projeto
30 |
31 | Agora que nós temos uma aplicação a ser testada nós podemos criar nosso primeiro teste. Nós iremos usar o [JUnit4](https://github.com/junit-team/junit4/wiki/getting-started) para executar os testes e a linguagem de programação Kotlin. O executor de testes é uma biblioteca que executa nosso código de teste e agrega os resultados de uma maneira amigável. Eu não irei entrar em detalhes sobre como realizar o setup de um projeto Android com testes escritos em Kotlin, porque já existe um excelente [artigo (em inglês)](http://fernandocejas.com/2017/02/03/android-testing-with-kotlin/) que descreve isso em detalhes. Você também pode ver o setup do projeto [Android-Testing-In-Kotlin](/app/build.gradle).
32 |
33 | ## Seu primeiro teste
34 |
35 | Para criar nosso primeiro teste nós temos que criar uma classe com métodos públicos anotados com `@org.junit.Test` na pasta `/src/test/kotlin`. Desse modo, nós falamos para o JUnit4 onde os testes estão localizados. Nós podemos iniciar com a checagem se o nosso app nos permite logar com os dados corretos. Nós queremos instrumentar [LoginRepository](/app/src/main/kotlin/com/example/unittesting/login/presenter/LoginPresenter.kt), para fazer isso eu preciso criar a classe [LoginRepositoryTest](/app/src/test/kotlin/com/example/unittesting/login/presenter/LoginPresenterTest.kt) com um método de teste. No começo nós queremos testar se é posssível logar com as credenciais corretas, então eu criei um método de teste com o nome `login with correct login and password`.
36 | ``` kotlin
37 | class LoginRepositoryTest {
38 |
39 | @Test
40 | fun `login with correct login and password`() {
41 |
42 | }
43 | }
44 | ```
45 | Em Kotlin nós podemos nomear os testes com nomes naturais como `login with correct login and password` mas isso somente se aplica para códigos que rodam na JVM. Testes unitários rodam apenas na JVM e nós podemos usar nomes descritivos.
46 |
47 | > Dica: Para suprimir o erro `Identifier not allowed for Android project...` exibido pelo Android Studio você deve ir até `Preferences... -> Editor -> Inspections -> Kotlin` e encontrar `Illegal Android Identifier` e então selecionar `Tests` em `In All Scopes` para desativar a checagem para os testes.
48 |
49 | ## Estrutura dos testes
50 |
51 | Cada teste deve ser criado a partir dos blocos seguintes:
52 |
53 | - Arrange/Given - onde nós preparamos todos os dados necessários para realizar o teste
54 | - Act/When - onde nós iremos chamar um único método no objeto testado
55 | - Assert/Then - onde nós iremos verificar o resultado do teste, se passou ou falhou
56 |
57 | JUnit4 não separa os blocos de teste de nenhum modo, então é recomendada a adição de comentários no código de teste. Principalmente, se você está iniciando sua jornada com testes.
58 |
59 | ``` kotlin
60 | @Test
61 | fun `login with correct login and password`() {
62 | //given
63 |
64 | //when
65 |
66 | //then
67 |
68 | }
69 | ```
70 | ## Bloco Given
71 |
72 | Nosso teste começa com o bloco `given` no qual nós poderemos preparar os dados do nosso teste e criar o objeto testado.
73 |
74 | Eu estou [criando a instância](https://kotlinlang.org/docs/reference/classes.html#creating-instances-of-classes) do objeto testado `LoginRepository` e atribuindo-o à uma [read-only property (propriedade somente de leitura)](https://kotlinlang.org/docs/reference/properties.html#declaring-properties). É muito conveniente distinguir objetos testados dos parâmetros do teste, assim eu irei chamá-lo de `objectUnderTest`. Você também pode nomeá-los: `sut`, `subject` ou `target`. Escolha o nome que se encaixa melhor na sua situação, apenas seja consistente através do projeto.
75 |
76 | Quando nós temos uma instância do objeto testado, então nós podemos seguir em frente para os parâmetros do teste. Desse modo, será `correctLogin` com o valor `'dbacinski'` e `correctPassword` com o valor `'correct'`. É muito importante escolher nomes significativos para cada parâmetro de teste, deve ser claro o tipo de valores que cada um deles contém.
77 |
78 | ``` kotlin
79 | @Test
80 | fun `login with correct login and password`() {
81 | //given
82 | val objectUnderTest = LoginRepository()
83 | val correctLogin = 'dbacinski'
84 | val correctPassword = `correct`
85 | //when
86 |
87 | //then
88 |
89 | }
90 | ```
91 |
92 | Agora o bloco `given` está concluído e nós podemos prosseguir.
93 |
94 | ## Block When
95 |
96 | No bloco `when` nós devemos chamar o método que nós queremos testar com os parâmetros preparados no bloco `given`. Então eu chamo o método `objectUnderTest.login(correctLogin, correctPassword)`. No bloco `when` nós devemos ter apenas uma linha de código para tornar claro o que realmente está sendo testado.
97 |
98 |
99 | ``` kotlin
100 | @Test
101 | fun `login with correct login and password`() {
102 | //given
103 | val objectUnderTest = LoginRepository()
104 | val correctLogin = 'dbacinski'
105 | val correctPassword = `correct`
106 | //when
107 | objectUnderTest.login(correctLogin, correctPassword)
108 | //then
109 |
110 | }
111 | ```
112 |
113 | ## Bloco Then
114 |
115 | É hora de verificar se o objeto testado retorna o valor esperado. Mas primeiro nós temos que armazenar o resultado do método testado na propriedade `val result` e então examiná-lo no bloco `then`. Agora nós temos que fazer uma asserção que verifica se o valor do resultado é o valor que estamos esperando. Isso irá lançar um erro quando a asserção não for satisfeita e o teste irá falhar.
116 | Nesse caso o objeto retornado é um Observable de RxJava 2 mas nós podemos convertê-lo facilmente para um `TestObserver` que é uma classe que fornece métodos de asserção. Eu estou checando se o valor do resultado é `true` de outro modo o resultado irá falhar.
117 |
118 | Testes de Observables de RxJava é um tópico para um artigo separado e eu não irei entrar em mais detalhes aqui.
119 | ``` kotlin
120 | @Test
121 | fun `login with correct login and password`() {
122 | //given
123 | val objectUnderTest = LoginRepository()
124 | val correctLogin = 'dbacinski'
125 | val correctPassword = `correct`
126 | //when
127 | val result = objectUnderTest.login(login, password)
128 | //then
129 | result.test().assertResult(true)
130 | }
131 | ```
132 | ## Executando os testes
133 |
134 | Nós podemos executar um teste pressionando `Ctrl + Shift + F10` no Android Studio/IntelliJ ou através de um Terminal usando o comando `./gradlew test`.
135 |
136 | Após executar o teste que nós escrevemos, você deve receber uma barra verde na IDE ou a saída `BUILD SUCCESSFUL` no Terminal.
137 |
138 |
139 |
140 |
141 | ## Falha no teste
142 |
143 | Quando a asserção do bloco `then` não for satisfeita então o teste irá falhar com a seguinte saída:
144 |
145 |
146 |
147 |
148 |
149 | Nós temos uma informação que o valor esperado deve ser `true` mas o valor atual retornado pelo objeto testado é `false`.
150 |
151 | ``` java
152 | java.lang.AssertionError:
153 | Values at position 0 differ; Expected: true (class: Boolean),
154 | Actual: false (class: Boolean) (latch = 0, values = 1, errors = 0, completions = 1)
155 | ```
156 |
157 | Nós também podemos ver que o teste que falhou tem o nome `login with correct login and password` e está na classe `LoginRepositoryTest`. A asserção falhou na linha `20` do arquivo `LoginRepositoryTest.kt`. Graças a uma mensagem de erro tão informativa, nós podemos ver exatamente qual asserção não foi satisfeita e corrigir o objeto testado.
158 |
159 | ``` java
160 | at com.example.unittesting.entity.login.LoginRepositoryTest
161 | .login with correct login and password(LoginRepositoryTest.kt:20)
162 | ```
163 |
164 | ## Conclusão
165 |
166 | Nessa altura você já está pronto para escrever seu primeiro teste unitário bem básico, executá-lo e examinar o que ocorreu de errado quando ele falhou. Fique ligado para o próximos tópicos mais avançados. Se você encontrou alguns erros se sinta livre para criar um Pull Request. Você também pode propor o próximo tópico relacionado à testes criando uma [Issue](https://github.com/dbacinski/Android-Testing-With-Kotlin/issues/new).
167 |
168 | Se você gostou do meu artigo, por favor não se esqueça de [dar uma :star:](https://github.com/dbacinski/Android-Testing-With-Kotlin/).
169 |
170 | #### Próximo: [Testes Unitários com Mockito 2 EN](/docs/Unit-Testing-Mockito.md)
171 |
172 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
10 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
11 | # When configured, Gradle will run in incubating parallel mode.
12 | # This option should only be used with decoupled projects. More details, visit
13 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
14 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dbacinski/Android-Testing-With-Kotlin/6a5ccf4ce270981846b1fe9f5778a056919abd0a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Oct 31 21:51:49 CET 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------