Kotlin Mvp Espresso


Source link: https://github.com/sallySalem/KotlinMvpEspresso

Kotlin Mvp Espresso

This example describes how use Espresso in Android-Kotlin Using MVP, Dagger2, Retrofit

Espresso is testing framework, provided by the Android Testing Support Library, provides APIs for writing UI tests to simulate user interactions. The steps for setup Espresso is the same steps if you use kotlin or java.

Espresso main components:

  • Espresso : ( onView() and onData()) Finds the view by using ViewMatchers.
  • ViewMatchers : ( withId()) Which can pass into the onView method to locate a view within the current view hierarchy.
  • ViewActions : ( perform()) Performs ViewActions for example: click().
  • ViewAssertions : ( check()) Validate the state of the currently selected view for example: isDisplayed().
Example:
Espresso.onView(ViewMatchers.withId(R.id.btn_submit))  .perform(ViewActions.click())  .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) 

Expresso packages:

  • Espresso-Core
  • Espresso-idling-resource
  • Espresso-Contrib (RecyclerViewActions)
  • Espresso-intents
  • Espresso-web Not included in this project

Espresso-Core :
Contains core and basic View matchers, actions, and assertions.

Example:
TextView
// check if tv_empty_data displayed on current screen  and contain no_data_available text onView(withId(R.id.tv_empty_data)).check(matches(isDisplayed()))  onView(withId(R.id.tv_empty_data)).check(matches(withText(R.string.no_data_available)))  
ReceycleView
onView(withId(R.id.rv_repositories_list)).check (matches (not (isDisplayed ())))  

matches (not (isDisplayed ()) will be true if the view is INVISIBLE or GONE you can check the visibility

onView(withId(R.id.rv_repositories_list)).check(matches(withEffectiveVisibility(Visibility.GONE)));
  

Be careful with the difference between asserting that a view is not displayed and asserting that a view is not present in the view hierarchy.

doesNotExist() Mean the view is not present in the view hierarchy, and this is different than not(Displayed()) not(Displayed()) Mean the view is in the view hierarchy but the visiblility is (INVISIBLE or GONE) or the view not displayed now in screen.

Example Snackbar:
onView(allOf(withId(android.support.design.R.id.snackbar_text),

 withText("Please enter github account name")))

  .check(doesNotExist());
  

allOf: used when looking through the various attributes of the views

onView(allOf(withId(R.id.but_show_repositories),

 withText("Show Repositories List"),

 isDisplayed()))

  .perform(click())  

Espresso-idling-resource:
Espresso waits until the UI is idle before it moves to the next operation. However, there are instances where applications perform background operations (such as communicating with web services) via non-standard means; for example: direct creation and management of threads. In such cases, you have to use Idling Resources for synchronization with background jobs.

The ways to implement Idling Resources:

  • Counting running jobs
  • Querying state
For example splash screen

I created SplashIdlingResource to wait for 3 sec (splash delay time) then inform Espresso

class SplashIdlingResource(private val waitingTime: Long) : IdlingResource {

private val startTime: Long

private var resourceCallback: ResourceCallback? = null

  init {

 this.startTime = System.currentTimeMillis()

}

  override fun getName(): String {

 return SplashIdlingResource::class.java.name + ":" + waitingTime

}

  override fun isIdleNow(): Boolean {

 val elapsed = System.currentTimeMillis() - startTime

 val idle = elapsed >= waitingTime

 if (idle) {

  resourceCallback!!.onTransitionToIdle()

 
}

 return idle

}

  override fun registerIdleTransitionCallback(resourceCallback: ResourceCallback) {

 this.resourceCallback = resourceCallback

}
  
}
  

Register it @Before and unRgigster it @After

Espresso-Contrib: (RecyclerViewActions) External contributions that contain DatePicker, RecyclerView and Drawer actions, accessibility checks, and CountingIdlingResource. In this example I will use RecyclerViewActions to scroll to a specific item. With out RecyclerviewActions you can only test the visible items on screen to test invisble item you have to scroll to position

onView(withId(R.id.rv_repositories_list))
  .perform(RecyclerViewActions.scrollToPosition<RepositoriesListAdapter.RepositoryItemViewHolder>(9))

 onView(

 allOf(withId(R.id.tv_repository_name),  withText("Flickr"), // we can set tag and test it withTagValue

isDisplayed())).check(matches(withText("Flickr")))  

Espresso-intents: Extension to validate and stub intents for hermetic testing. Here you can mock the intent and to be sure if app navigate to correct intent or not.

To use Espresso-intents:

  • Use the IntentsTestRule instead of ActivityTestRule.
  • Or init Intents at @Before and release it at @After
// is an equivalent of verify(mock, times(1)) in Mockito  Intents.intended(IntentMatchers.hasComponent(RepositoriesListActivity::class.java.name))  

Note

  • It is recommended to turn of the animation on the Android device which is used for testing. Animations might confusing Espressos check for ideling resources
  • Espresso tests must be placed in the app/src/androidTest folder.

Refrence:

Resources

EditText component which shows bouncy hint.

Plugin for JetBrains IDEs which allows to generate POJO classes using JSON code snippets.

Loading view with pretty animation.

ExpandableView is a View showing only a content and when clicked on it, it displays more content in a fashion way. You can add views or viewgroups but remember that it will only display the content in a LinearLayout with vertical orientation.

Add views to a FlowLayout and each view is put to the right of the previous one and wraps to a new row when the current row is full.

The Android implementation of Replace. The content of the layout can be any view, such as ListView, RecyclerView, ScrollView, etc.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes