How to test a Fragment using Espresso
What is a Fragment in Espresso?
How to quiz a Fragment using Espresso
What is a Fragment in Espresso?
Fragment represents the behavior of the user interface of an action. Multiple fragments can be used together in a single activity and once a fragment is created it can be reused multiple times. A sherd has its own living cycle and It has its own comment and corresponding output.
AndroidComposeTestRulewas designed for the use case where compose content is hosted by an Activity. This examination regulation allows access to the activity and thus its Navigation Controller. It is needed to successfully navigate to the various fragments of the application.
How to Set up for Espresso Fragment Test
Step 1Add the following dependencies
androidTestImplementation ('androidx.test.espresso: espresso-intents:3.4.0 ') androidTestImplementation (`` androidx.compose.ui: ui-test-junit4:1.0.0 '')Here,
Espresso Intents: Validate the click listeners that start new activities.
Compose: Verify the correct conduct of your Compose codification
Step 2 Add the testInstrumentationRunnerusing the code written below
defaultConfig {testInstrumentationRunner `` androidx.test.runner.AndroidJUnitRunner ''} Due to a configuration issue, I also needed to add the following packaging options to get the tests to make: packagingOptions {resources.excludes += `` META-INF/AL2.0 '' resources.excludes += `` META-INF/LGPL2.1 ''}Writing tests for Fragment Testing expend Espresso
The exam will start by pilot to our shard usingAndroidComposeTestRule. Before each test, we use the test rule to derive access to the activeness ’ snavControllerand so navigate to the especial fragment.
@ get: Rule val composeTestRule = createAndroidComposeRule & lt; GardenActivity & gt; () @ Before fun jumpToPlantDetailFragment () {composeTestRule.activityRule.scenario.onActivity {val bundle = Bundle () .apply {putString (`` plantId '', `` mangifera-indica '')} findNavController (it, R.id.nav_host) .navigate (R.id.plant_detail_fragment, bundle)}}Our first Test. We want to confirm that the static screen constituent are displayed.
@ Test fun screen_launches () {composeTestRule.onNodeWithText (`` Mango '') .assertIsDisplayed ()}The composeTestRulehas a purposeonNodeWithTextthat allows you to find a composable with a especial textbook. If the composable is found you can make assorted assertions. For this simple case, we only desire to ensure that the ingredient with text is displayed.
Our 2nd Test.We want to confirm that on sharing particular schoolbook on the share intent is displayed.
@ Test fun testShareTextIntent () {Intents.init () composeTestRule.onNodeWithText (`` Mango '') .assertIsDisplayed () composeTestRule.onNodeWithContentDescription (`` Share '') .assertIsDisplayed () .performClick () intended (chooser (allOf (hasAction (Intent.ACTION_SEND), hasType (`` text/plain ''), hasExtra (Intent.EXTRA_TEXT, '' Check out the Mango plant in the Android Sunflower app '')))) Intents.release () // dismiss the Share Dialog InstrumentationRegistry.getInstrumentation () .uiAutomation .performGlobalAction (AccessibilityService.GLOBAL_ACTION_BACK)}We click on the share button of the fragment when it is expose and check on sharing the exceptional schoolbook on the Intent is display.
Run Fragment Test in Espresso
Create a test configuration In Android Studio:
- Open Run menu >>Edit Configurations
- Add a new Android Tests configuration
- Choose a faculty
- Add a specific instrumentation contrabandist using the below dictation:
android.support.test.runner.AndroidJUnitRunner
Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.
- Add your grade gens
Once the configuration is set up connect your gimmick or select the ape and directly run the configuration.
Executing Fragment Test in Espresso with BrowserStack
For more accurate results, it is recommended to test on real device using, direct into account.
With BrowserStack ’ s you can run Espresso Toast Message on real device by follow the steps below:
Step 1 To Run your test cases on BrowserStack you need two apk file.
First one is themain app.apk file and another is yourandroidTest.apk file.
To generate both the apk run below command
- To make a.apkfile for the app run the following command in the terminal:
./gradlew assembleDebug
- To create a.apkfile for the test assort in the terminal run the following bidding:
./gradlew assembleAndroidTest
Find both .apk file under your project pamphlet: & lt; project-folder & gt; \build\outputs\apk. In the apk folder you will find two files:
- app-debug.apk
- app-debug-androidTest.apk
These are the file that you will upload to the cloud when you create your Execution Plan.
Step 2Get your accession key from the BrowserStack using the below command
coil -u `` & lt; username & gt;: & lt; access-key & gt; '' -X POST `` https: //api-cloud.browserstack.com/app-automate/upload '' -F `` file= @ /path/to/app/file/Application-debug.apk ''
Output
Please note the App URL (bs: // & lt; hashed appid & gt;) returned in the reaction of this call:
{`` app_url '': '' bs: // & lt; hashed appid & gt; ''}Step 3Upload the app by lam below command on your end
curl -u `` & lt; username & gt;: & lt; access-key & gt; '' -X POST `` https: //api-cloud.browserstack.com/app-automate/espresso/v2/test-suite '' -F `` file= @ /path/to/test/file/Application-debug-test.apk ''
Output
Please note the Test Suite URL (bs: // & lt; hash testID & gt;) returned in the reply of this call:
{`` test_url '': '' bs: // & lt; hashed testID & gt; ''}The Test ID returned in the response will be used to execute your test.
Conclusion
To get more accurate results, it is advocate to for testing, so as to take into history. Which is why tool like are real useful to test on real Android devices.
It allows you try over a wide scope of Android devices from the latest one like Google Pixel 9, Samsung Galaxy S24, and Galaxy Z Fold 6 made available for screen from Day 0 to the legacy device. It also has Redmi, Oppo, Vivo and Motorola devices to test on.
BrowserStack App Automate makes debugging easier by grant QAs to check the video, text, and console logs, which can be share with the squad over Slack, GitHub, Trello or Jira.
# Ask-and-Contributeabout this topic with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free