Share
Embed
Transcript
143 slides
-
What Software testing is an investigation conducted to provide stakeholders
with information about the quality of the software product or service under test. Software testing can also provide an objective, independent view of the software to allow the business to appreciate and understand the risks of software implementation. Test techniques include the process of executing a program or application with the intent of finding software bugs (errors or other defects), and verifying that the software product is fit for use. -
What Software testing is an investigation conducted to provide stakeholders
with information about the quality of the software product or service under test. Software testing can also provide an objective, independent view of the software to allow the business to appreciate and understand the risks of software implementation. Test techniques include the process of executing a program or application with the intent of finding software bugs (errors or other defects), and verifying that the software product is fit for use. Process to check software quality and to push us to work more. -
Unit testing Unit tests are the fundamental tests in your
app testing strategy. By creating and running unit tests against your code, you can easily verify that the logic of individual unit is correct. Running unit tests after every build helps you to quickly catch and fix software regressions introduced by code changes to your app. -
Unit testing Unit tests are the fundamental tests in your
app testing strategy. By creating and running unit tests against your code, you can easily verify that the logic of individual units is correct. Running unit tests after every build helps you to quickly catch and fix software regressions introduced by code changes to your app. -
class UnitTest { <- test class fun `test 2 plus
2 is 4`() { <- test function assertEquals(4, 2 + 2) <- assertion } } -
class UnitTest { <- test class @Test <- @Test annotation
to mark function as test fun `test 2 plus 2 is 4`() { <- test function assertEquals(4, 2 + 2) <- assertion } } -
class UnitTest { <- test class @Test <- @Test annotation
to mark function as test fun `test 2 plus 2 is 4`() { <- test function assertEquals(4, 2 + 2) <- assertion } } @Suite.SuiteClasses(UnitTest::class) <- suite -
AAA - Arrange, Act, Assert @Test fun `test 2 plus
4 is 4`() { // arrange (initialize) val first = 2 val second = 2 // act (do job) val result = first + second // assert (verify) assertEquals(4, result) } -
JUnit @Before <- before each test function @After <- after
each test function @BeforeClass <- before execution of test class (static context) @AfterClass <- after execution of test class (static context) -
Android Unit testing Unit tests that run on your local
machine only. These tests are compiled to run locally on the Java Virtual Machine (JVM) to minimize execution time. If your tests depend on objects in the Android framework, we recommend using Robolectric. For tests that depend on your own dependencies, use mock objects to emulate your dependencies' behavior. -
Android Unit testing Unit tests that run on your local
machine only. These tests are compiled to run locally on the Java Virtual Machine (JVM) to minimize execution time. If your tests depend on objects in the Android framework, we recommend using Robolectric. For tests that depend on your own dependencies, use mock objects to emulate your dependencies' behavior. -
class LoginRepository(private val dataSource: DataSource) { fun login(login: String, password:
String): User = dataSource.login(login, password) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val loginRepository = LoginRepository(dataSource) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = object : DataSource { override fun login(login: String, password: String): User = user } val loginRepository = LoginRepository(dataSource) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = object : DataSource { override fun login(login: String, password: String): User = user } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = object : DataSource { override fun login(login: String, password: String): User = user } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") var called = false val dataSource = object : DataSource { override fun login(login: String, password: String): User { called = true return user } } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) assertTrue(called) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") var called = false val dataSource = object : DataSource { override fun login(login: String, password: String): User { Is proper login/pass passed? called = true return user } } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) assertTrue(called) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") var called = false val dataSource = object : DataSource { What if DataSource is final class? override fun login(login: String, password: String): User { Is proper login/pass passed? called = true return user } } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) assertTrue(called) } -
MockK https://mockk.io/ • Mocking • Object, Constructor, Extensions mocking •
DSL • Verification order -
MockK https://mockk.io/ • Mocking • Object, Constructor, Extensions mocking •
DSL • Verification order • Coroutines • … and much more -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") var called = false val dataSource = object : DataSource { What if DataSource is final class? override fun login(login: String, password: String): User { Is proper login/pass passed? called = true return user } } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) assertTrue(called) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = mockk<DataSource>() { every { login(any(), any()) } returns user } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) } -
inline fun <reified T : Any> mockk( name: String? =
null, relaxed: Boolean = false, vararg moreInterfaces: KClass<*>, relaxUnitFun: Boolean = false, block: T.() -> Unit = {} ) -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = mockk<DataSource>() { every { login(any(), any()) } returns user } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") assertEquals(user, userResult) } -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = mockk<DataSource>() { every { login(any(), any()) } returns user } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") verify { dataSource.login("User", "Password") } assertEquals(user, userResult) } -
fun verify( ordering: Ordering = Ordering.UNORDERED, inverse: Boolean = false,
atLeast: Int = 1, atMost: Int = Int.MAX_VALUE, exactly: Int = -1, timeout: Long = 0, verifyBlock: MockKVerificationScope.() -> Unit ) -
@Test fun `test login should return user from data source`()
{ val user = User(0, "KLUG") val dataSource = mockk<DataSource>() { every { login(any(), any()) } returns user } val loginRepository = LoginRepository(dataSource) val userResult = loginRepository.login("User", "Password") verify { dataSource.login("User", "Password") } assertEquals(user, userResult) } -
Object @Test fun `object mocking`() { assertEquals(1, Object.returnOne()) mockkObject(Object) every
{ Object.returnOne() } returns 2 assertEquals(2, Object.returnOne()) unmockkObject(Object) assertEquals(1, Object.returnOne()) } -
Extensions @Test fun `extensions mocking`() { mockkStatic("kotlin.io.FilesKt__UtilsKt") or class with
extensions every { File("/").deleteRecursively() } returns true assertTrue(File("/").deleteRecursively()) unmockkStatic("kotlin.io.FilesKt__UtilsKt") } -
Extensions @Test fun `extensions mocking`() { mockkStatic("kotlin.io.FilesKt__UtilsKt") or class with
extensions every { File("/").deleteRecursively() } returns true assertTrue(File("/").deleteRecursively()) unmockkStatic("kotlin.io.FilesKt__UtilsKt") } every { File("/").deleteRecursively() } answers { throw Exception("") } -
Switch implementation @Test fun `switch implementation`() { val scheme =
Uri.parse("http://myuri").scheme assertEquals("http", scheme) } -
Switch implementation @Test fun `switch implementation`() { val scheme =
Uri.parse("http://myuri").scheme assertEquals("http", scheme) } java.lang.RuntimeException: Method parse in android.net.Uri not mocked. -
package android.net; public abstract class Uri implements Comparable<Uri>, Parcelable {
public static Uri parse(String uriString) { return new Uri() { … } public String getScheme() { return "http"; } } -
LiveData & ViewModel class LoginViewModel( private val repository: Repository )
: ViewModel() { private val _userLiveData = MutableLiveData<User>() val userLiveData: LiveData<User> = _userLiveData fun login(email: String, pass: String) { viewModelScope.launch(Dispatchers.IO) { val user = repository.login(email, pass) _userLiveData.postValue(user) } … -
@Test fun `test login`() { val repository = mockk<Repository>() val
observer = mockk<Observer<User>>() val viewmodel = LoginViewModel(repository) viewmodel.userLiveData.observeForever(observer) viewmodel.login("email", "pass") verify { observer.onChanged(any()) } } -
@Test fun `test login`() { val repository = mockk<Repository>() val
observer = mockk<Observer<User>>() val viewmodel = LoginViewModel(repository) viewmodel.userLiveData.observeForever(observer) viewmodel.login("email", "pass") _userLiveData.postValue(user) verify { observer.onChanged(any()) } } -
@get:Rule val rule = InstantTaskExecutorRule() @Test fun `test login`() {
val repository = mockk<Repository>() val observer = mockk<Observer<User>>() val viewmodel = LoginViewModel(repository) viewmodel.userLiveData.observeForever(observer) viewmodel.login("email", "pass") verify { observer.onChanged(any()) } } -
@get:Rule val rule = InstantTaskExecutorRule() @Test viewModelScope.launch(Dispatchers.IO) fun `test login`()
{ val repository = mockk<Repository>() val observer = mockk<Observer<User>>() val viewmodel = LoginViewModel(repository) viewmodel.userLiveData.observeForever(observer) viewmodel.login("email", "pass") verify { observer.onChanged(any()) } } -
class LoginViewModel( private val repository: Repository, private val dispatcher: CoroutineDispatcher
) : ViewModel() … @Test fun `test login`() { … val viewmodel = LoginViewModel(repository, Dispatchers.Unconfined) … } -
• Data should be static • Different sets of data
• Server errors, can’t emulate all -
• Data should be static • Different sets of data
• Server errors, can’t emulate all • Authenticate each test run -
• Data should be static • Different sets of data
• Server errors, can’t emulate all • Authenticate each test run • Response duration -
• Data should be static • Different sets of data
• Server errors, can’t emulate all • Authenticate each test run • Response duration • Can be down -
• Data should be static • Different sets of data
• Server errors, can’t emulate all • Authenticate each test run • Response duration • Can be down • This is AQA work -
• You decide whether to do error or what data
to return • Tests and app components are independent of each other -
• You decide whether to do error or what data
to return • Tests and app components are independent of each other • Do not rely on anything except app -
• You decide whether to do error or what data
to return • Tests and app components are independent of each other • Do not rely on anything except app • You’re the BOSS here -
MockWebServer https://github.com/square/okhttp/tree/master/mockwebserver • Behaves like a real back-end • Enqueue
responses • No response delay -
MockWebServer https://github.com/square/okhttp/tree/master/mockwebserver • Behaves like a real back-end • Enqueue
responses • No response delay • Full control -
Mock ViewModel val userLiveData = MutableLiveData<User>() val viewModel = mockk<LoginViewModel>()
{ every { user } returns userLiveData } -
Mock ViewModel val userLiveData = MutableLiveData<User>() val viewModel = mockk<LoginViewModel>()
{ every { user } returns userLiveData } injectViewModel(viewModel) rule.launchActivity(null) userLiveData.postValue(User(0, "Markiyan")) -
Mock ViewModel val userLiveData = MutableLiveData<User>() val viewModel = mockk<LoginViewModel>()
{ every { user } returns userLiveData } injectViewModel(viewModel) rule.launchActivity(null) userLiveData.postValue(User(0, "Markiyan")) -
class LoginViewModel( private val repository: Repository, private val dispatcher: CoroutineDispatcher
) : ViewModel() { val user = MutableLiveData<User>() val loading = MutableLiveData<Boolean>() val error = MutableLiveData<Throwable>() … -
open class LoginViewModel( private val repository: Repository, private val dispatcher:
CoroutineDispatcher ) : ViewModel() { open val user = MutableLiveData<User>() open val loading = MutableLiveData<Boolean>() open val error = MutableLiveData<Throwable>() … -
All-Open https://kotlinlang.org/docs/reference/compiler-plugins.html#all-open-compiler-plugin plugins { id "org.jetbrains.kotlin.plugin.allopen" version "1.3.61" } annotation
class OpenForTesting allOpen { annotation("com.klug.testtodo.OpenForTesting") } -
@OpenForTesting class LoginViewModel( private val repository: Repository, private val dispatcher:
CoroutineDispatcher ) : ViewModel() { val user = MutableLiveData<User>() val loading = MutableLiveData<Boolean>() val error = MutableLiveData<Throwable>() … -
@OpenForTesting class LoginViewModel( private val repository: Repository, private val dispatcher:
CoroutineDispatcher ) : ViewModel() { val user = MutableLiveData<User>() val loading = MutableLiveData<Boolean>() val error = MutableLiveData<Throwable>() … -
Test @Test fun testLogin() { onView(withId(R.id.etLogin)).perform(typeText("login")) onView(withId(R.id.etPassword)).perform(typeText("password")) onView(withId(R.id.btnLogin)).perform(click()) onView(withId(R.id.imgUserAvatar)).check(matches(isDisplayed())) onView(withId(R.id.tvUserName))
.check(matches(allOf(isDisplayed(), withText("User Name")))) } -
Use extensions private fun Int.asView() = onView(withId(this)) fun ViewInteraction.click() =
perform(ViewActions.click()) fun Int.click() = asView().click() -
Use extensions private fun Int.asView() = onView(withId(this)) fun ViewInteraction.click() =
perform(ViewActions.click()) fun Int.click() = asView().click() infix fun ViewInteraction.typeText(text: String) = perform(ViewActions.typeText(text)) infix fun Int.typeText(text: String) = asView().typeText(text) -
Use extensions private fun Int.asView() = onView(withId(this)) fun ViewInteraction.click() =
perform(ViewActions.click()) fun Int.click() = asView().click() infix fun ViewInteraction.typeText(text: String) = perform(ViewActions.typeText(text)) infix fun Int.typeText(text: String) = asView().typeText(text) import <your.package.name>.R.id.* -
@Test fun testLogin() { etLogin typeText "login" etPassword typeText "password"
btnLogin.click() imgUserAvatar.isDisplayed() tvUserName.isDisplayed() withText "User Name" } -
Test @Test fun testLogin() { onView(withId(R.id.etLogin)).perform(typeText("login")) onView(withId(R.id.etPassword)).perform(typeText("password")) onView(withId(R.id.btnLogin)).perform(click()) onView(withId(R.id.imgUserAvatar)).check(matches(isDisplayed())) onView(withId(R.id.tvUserName))
.check(matches(allOf(isDisplayed(), withText("User Name")))) } -
Espresso Packages • Core - Matchers, Actions • Intents -
Intents - record, stub, verify -
Espresso Packages • Core - Matchers, Actions • Intents -
Intents - record, stub, verify • Web - WebView testing -
Espresso Packages • Core - Matchers, Actions • Intents -
Intents - record, stub, verify • Web - WebView testing • Remote - Multi-process testing -
Espresso Packages • Core - Matchers, Actions • Intents -
Intents - record, stub, verify • Web - WebView testing • Remote - Multi-process testing • Contrib - RecyclerView, Drawer, DatePicker -
Espresso Packages • Core - Matchers, Actions • Intents -
Intents - record, stub, verify • Web - WebView testing • Remote - Multi-process testing • Contrib - RecyclerView, Drawer, DatePicker • Idling resource - Synchronize jobs -
UI loading something, custom animations IdlingResource Espresso's mechanism for synchronization
with background jobs. • CountingIdlingResource • UriIdlingResource • IdlingThreadPoolExecutor / ScheduledIdlingThreadPoolExecutor -
Idling Resource implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' object SplashIdlingResource : IdlingResource { override
fun isIdleNow(): Boolean override fun registerIdleTransitionCallback(callback) } -
Idling Resource implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' object SplashIdlingResource : IdlingResource { override
fun isIdleNow(): Boolean = isIdle override fun registerIdleTransitionCallback(callback) { this.callback = callback } } -
Idling Resource implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' object SplashIdlingResource : IdlingResource { override
fun isIdleNow(): Boolean = isIdle override fun registerIdleTransitionCallback(callback) { this.callback = callback } fun notifyJobStarted() fun notifyJobFinished() } -
Idling Resource implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0' object SplashIdlingResource : IdlingResource { override
fun isIdleNow(): Boolean = isIdle override fun registerIdleTransitionCallback(callback) { this.callback = callback } fun notifyJobStarted() { isIdle = false } fun notifyJobFinished() { isIdle = true callback?.onTransitionToIdle() } -
Idling Resource object SplashIdlingResource : IdlingResource { override fun isIdleNow():
Boolean = isIdle override fun registerIdleTransitionCallback(callback) { this.callback = callback } fun notifyJobStarted() { isIdle = false } fun notifyJobFinished() { isIdle = true callback?.onTransitionToIdle() } IdlingRegistry.getInstance().register(SplashIdlingResource) -
Single-Activity inline fun <reified F : Fragment> launchFragmentInContainer( fragmentArgs: Bundle?
= null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory? = null ) -
Single-Activity inline fun <reified F : Fragment> launchFragmentInContainer( fragmentArgs: Bundle?
= null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory? = null ) moveToState(Lifecycle.State) -
Single-Activity inline fun <reified F : Fragment> launchFragmentInContainer( fragmentArgs: Bundle?
= null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory? = null ) moveToState(Lifecycle.State) recreate() -
Single-Activity inline fun <reified F : Fragment> launchFragmentInContainer( fragmentArgs: Bundle?
= null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory? = null ) moveToState(Lifecycle.State) recreate() onFragment {} -
Setup classpath "com.vanniktech:gradle-android-junit-jacoco-plugin:0.15.0" apply plugin: "com.vanniktech.android.junit.jacoco" junitJacoco { jacocoVersion =
'0.8.5' includeInstrumentationCoverageInMergedReport = false } -
Setup classpath "com.vanniktech:gradle-android-junit-jacoco-plugin:0.15.0" apply plugin: "com.vanniktech.android.junit.jacoco" junitJacoco { jacocoVersion =
'0.8.5' includeInstrumentationCoverageInMergedReport = false } ./gradlew jacocoTestReportDebug