Unit Testing In Android - Introduction
Unit Testing in Android is a method of testing the small unit of code. The most important concept of this Unit Testing is to focus on testing the small unit of code that affects the whole behaviour of the App.
Why Unit Testing ?
- Improves the quality of code
- Detects software bugs
- Provides code reusability and reliability
- Reduce cost and development time
Unit Test Framework we used in Android is called : JUnit
// dependencies for local unit tests
testImplementation 'junit:junit:4.+'
// AndroidX Test - Instrumentation Testing
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
Important concepts:
- Non of the test code is included in final apk.
- App code Cannot access testing code
- test libraries are only included in test source set and it is mapped by .gradle configuration. Dependencies scoped with testImplementation and androidTestImplementation
Difference between test and androidTest Source sets:
test
- Local tests
- Run on local machine JVM
- Run much faster, but less fidelity
androidTest
- Instrumented Tests
- Run on Real or emulated devices
- But they run much slower, but more fidelity
*Fidelity : It means how "realistic" the test is
@RunWith(AndroidJUnit4::class)
This is responsible to define how your test runs.
Organising your Test:
We need to make our tests readable because it's a kind of a documentation of our code.
We follow this strategy : Given_When_Then
subjectUnderTest_actionOrInput_resultState
eg. givenNumber_whenDoneSquare_thenResultOfNumberInSquare()
Tips: You could also used Assertion Frameworks like Hamcrest and Truth Library to make your test more readable and human friendly.
Testing Strategy:
We divide the Automated testing code in different groups like :
- Unit Test - 70%
- Integration Test - 20%
- End to End Tests - 10%
Example:
- Unit Test - ViewModel, Repository, DAO
- Integration Test - Activity, Fragment, ViewModel, Database
- End to End Tests - Whole App
Comments
Post a Comment