<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sonu Gupta on Medium]]></title>
        <description><![CDATA[Stories by Sonu Gupta on Medium]]></description>
        <link>https://medium.com/@sonu-gupta?source=rss-69ebe23485de------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KRPg7Xr7PpudjbYu8T-O7g.jpeg</url>
            <title>Stories by Sonu Gupta on Medium</title>
            <link>https://medium.com/@sonu-gupta?source=rss-69ebe23485de------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:37:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sonu-gupta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Playwright Java Framework from Scratch: What I Learnt]]></title>
            <link>https://sonu-gupta.medium.com/building-a-playwright-java-framework-from-scratch-what-i-learnt-dc881ac129dc?source=rss-69ebe23485de------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc881ac129dc</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[ai-testing]]></category>
            <dc:creator><![CDATA[Sonu Gupta]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 10:21:55 GMT</pubDate>
            <atom:updated>2026-11-27T05:37:08.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kC809CFBhMwYPgXxOtWjQ.png" /></figure><h3>Why I built it</h3><p>I started learning Playwright the way most people do: one test class at a time, with the browser, URLs and logins written straight into each test. It worked, until I wanted to run the same tests on Firefox, point them at another environment, or run them on every push.</p><p>This article walks through how those learning scripts became a small but real test framework, using code from my own repo. It also covers the mistakes that cost me the most time, because those are the parts tutorials usually skip.</p><p>The stack:</p><ul><li><strong>Playwright for Java 1.64.0</strong> — browser automation and API calls</li><li><strong>TestNG 7.12.0</strong> — test runner, suites, groups and data providers</li><li><strong>Gradle 9.6.0 (wrapper)</strong> — build and test execution</li><li><strong>Java 25</strong> — language (17 or newer works)</li><li><strong>GitHub Actions</strong> — CI on every push and pull request</li></ul><p>The app under test is EventHub, a practice event-booking site. The main end-to-end test logs in, creates an event as an admin, finds it on the Events page and books tickets.</p><p>I learnt the foundations from Rahul Shetty’s <a href="https://www.udemy.com/course/playwright-java-automation-testing-framework/">Playwright Java automation testing course on Udemy</a>. EventHub is his academy’s practice site. This article is my own write-up of what I built and the problems I hit along the way.</p><p>Each step below fixes one problem with those early scripts, from page objects through to tracing and CI. It ends with API testing and mocking as a bonus, and three bugs worth knowing about before you hit them.</p><h3>Where I started: learning scripts</h3><p>My first test, BasicTest, did everything inside one class. Setup launched Chromium, opened the login URL and started a trace:</p><pre>@BeforeMethod<br>public void setUp() {<br>    Playwright playwright = Playwright.create();<br>    Browser browser = playwright.chromium().launch(<br>            new BrowserType.LaunchOptions().setHeadless(false));<br>    context = browser.newContext();<br>    page = context.newPage();<br>    page.navigate(&quot;https://eventhub.rahulshettyacademy.com/login&quot;);<br>}</pre><p>The test itself then filled the login form, went to the admin page and created an event, all with raw locators:</p><pre>page.getByPlaceholder(&quot;you@email.com&quot;).fill(&quot;&lt;test-user&gt;&quot;);<br>page.getByLabel(&quot;Password&quot;).fill(&quot;&lt;test-password&gt;&quot;);<br>page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName(&quot;Sign In&quot;)).click();<br>page.navigate(&quot;https://eventhub.rahulshettyacademy.com/admin/events&quot;);<br>page.locator(&quot;#event-title-input&quot;).fill(&quot;Playwright Demo&quot;);</pre><p>This is a great way to learn the API. It stops scaling as soon as you have a second test:</p><ul><li><strong>The browser is fixed.</strong> Switching to Firefox means editing every class.</li><li><strong>The URL is fixed.</strong> There is no way to point the suite at another environment.</li><li><strong>Locators are copied around.</strong> When the login form changes, every test that logs in breaks.</li><li><strong>Test data lives in code.</strong> Running the same flow with different data means copying the test.</li></ul><p>I kept these learning classes in the repo as reference, and built the framework next to them. Each of the next sections fixes one of the problems above.</p><h3>Step 1: Page objects for every screen</h3><p>The first change was moving each screen’s locators and actions into its own class. A test then reads like the user journey, and a UI change is fixed in one place.</p><p>The repo has one page object per screen:</p><pre>src/test/java/pages/<br>├── LoginPage.java<br>├── DashboardPage.java<br>├── AdminEventsPage.java<br>├── EventsPage.java<br>├── BookingFormPage.java<br>├── MyBookingsPage.java<br>└── BookingDetailsPage.java</pre><p>EventsPage shows the pattern: locator names as constants at the top, then small methods that describe what the user does.</p><pre>public class EventsPage {<br>    Page page;<br>    private static final String navEvents = &quot;#nav-events&quot;;<br>    private static final String eventCard = &quot;event-card&quot;;<br>    private static final String bookNowBtn = &quot;book-now-btn&quot;;<br>    private Locator eventCards;<br>    private Locator targetCard;<br>public EventsPage(Page page) {<br>        this.page = page;<br>    }<br>    public void waitForEventsToLoad() {<br>        eventCards = page.getByTestId(eventCard);<br>        assertThat(eventCards.first()).isVisible();<br>    }<br>    public void proceedToBooking() {<br>        targetCard.getByTestId(bookNowBtn).click();<br>    }<br>}</pre><p>With page objects in place, the main test reads as the journey itself:</p><pre>LoginPage loginPage = new LoginPage(page, baseURL);<br>loginPage.login();<br><br>AdminEventsPage adminEventsPage = new AdminEventsPage(page, baseURL);<br>adminEventsPage.goToEventsPage();<br>adminEventsPage.createEvent(eventTitle, description, category, city,<br>        venue, dateTime, price, totalSeats);<br>EventsPage eventsPage = new EventsPage(page);<br>eventsPage.goToEventsPage();<br>eventsPage.waitForEventsToLoad();<br>eventsPage.findEventCard(eventTitle);<br>eventsPage.proceedToBooking();</pre><p>A few locator habits that paid off:</p><ul><li><strong>Prefer user-facing locators.</strong> getByRole, getByLabel and getByPlaceholder find elements the way a user would, and survive CSS changes.</li><li><strong>Use test ids when the team adds them.</strong> getByTestId(&quot;event-card&quot;) reads the data-testid attribute and is the most stable option.</li><li><strong>Keep CSS as a last resort.</strong> #admin-event-form textarea works, but breaks when the layout changes.</li><li><strong>Lean on auto-waiting assertions.</strong> assertThat(locator).isVisible() retries until the element appears, so you rarely need a sleep.</li><li><strong>Assert, don’t just check.</strong> locator.isVisible() returns true or false straight away, and nothing fails when it is false. My first toast check, page.getByText(&quot;Event Created!&quot;).isVisible();, could never fail a test. assertThat(locator).isVisible() waits and fails the test when the element doesn&#39;t appear.</li></ul><h3>Step 2: A browser factory in a base class</h3><p>The learning scripts each launched Chromium themselves. In the framework, a single BaseTest class launches the browser, and every framework test extends it. Which browser it launches is decided at run time:</p><pre>public class BaseTest {<br>    Playwright playwright;<br>    Browser browser;<br>    Page page;<br>    String baseURL;<br><br>    @BeforeMethod(alwaysRun = true)<br>    public void setUp() throws IOException {<br>        // ... load config.properties into prop (step 3)<br>        String browserName = System.getProperty(&quot;browser&quot;) != null<br>                ? System.getProperty(&quot;browser&quot;) : prop.getProperty(&quot;browser&quot;);<br><br>        playwright = Playwright.create();<br><br>        // Headless on CI (no display there), headed locally<br>        boolean headless = System.getenv(&quot;CI&quot;) != null;<br>        BrowserType.LaunchOptions opts = new BrowserType.LaunchOptions().setHeadless(headless);<br><br>        if (&quot;firefox&quot;.equalsIgnoreCase(browserName)) {<br>            browser = playwright.firefox().launch(opts);<br>        } else if (&quot;safari&quot;.equalsIgnoreCase(browserName)) {<br>            browser = playwright.webkit().launch(opts);<br>        } else {<br>            browser = playwright.chromium().launch(opts);<br>        }<br>        page = browser.newPage();<br>    }<br>}</pre><ul><li>chrome (also the fallback) → Chromium</li><li>firefox → Firefox</li><li>safari → WebKit, the engine behind Safari</li></ul><p>Setup has a partner: a teardown that closes what it opened. Without it, every test leaves a browser process running, which slows the machine down and can crash long parallel runs:</p><pre>@AfterMethod(alwaysRun = true)<br>public void tearDown() {<br>    if (browser != null) browser.close();<br>    if (playwright != null) playwright.close();<br>}</pre><p>A test only asks for a page; it never knows or cares which browser it got:</p><pre>public class FrameworkBuildDataDrivenTest extends BaseTest {<br>    // page and baseURL are ready to use<br>}</pre><p>Two details worth copying:</p><ul><li><strong>Headless based on the </strong><strong>CI variable.</strong> GitHub Actions sets CI=true, so tests open a visible browser on my laptop and run headless on the CI server, which has no display.</li><li><strong>Fail on unknown names, if you want to be strict.</strong> Any value other than firefox or safari falls back to Chromium, so a typo such as firfox quietly runs on Chromium. Throwing an error in a default branch catches that.</li></ul><h3>Step 3: Global settings in one properties file</h3><p>Settings that apply to the whole run live in one file, src/test/resources/config.properties:</p><pre>browser=firefox<br>env=qa<br>qa.baseurl=https://eventhub.rahulshettyacademy.com/login<br>prod.baseurl=https://prod.eventhub.rahulshettyacademy.com/login<br>dev.baseurl=https://google.com</pre><p>BaseTest loads it before every test, picks the environment, then builds the key for that environment&#39;s URL:</p><pre>try (FileInputStream fis =<br>    new FileInputStream(<br>      &quot;src/test/resources/config.properties&quot;)) {<br>  prop.load(fis);  // try-with-resources closes the file<br>}<br><br>String envName = System.getProperty(&quot;env&quot;) != null<br>        ? System.getProperty(&quot;env&quot;) : prop.getProperty(&quot;env&quot;);<br>baseURL = prop.getProperty(envName + &quot;.baseurl&quot;);   // env=qa -&gt; qa.baseurl</pre><p>The &lt;env&gt;.baseurl naming pattern means adding an environment is one new line in the file, with no code change. Tests receive baseURL from BaseTest and pass it to LoginPage, so none of them contain a URL.</p><p>In my repo only qa is a real site; prod and dev are placeholders that show how switching works.</p><p>The properties file holds the defaults. Step 8 shows how to override them for a single run from the command line, which is how CI picks the browser and environment.</p><h3>Step 4: Data-driven tests from JSON</h3><p>To run the same booking flow with different data, I moved the data out of the test into a JSON array. Each object becomes one test run:</p><pre>[<br>  {<br>    &quot;titlePrefix&quot;: &quot;Playwright Demo&quot;,<br>    &quot;category&quot;: &quot;Workshop&quot;,<br>    &quot;city&quot;: &quot;Bokaro&quot;,<br>    &quot;dateTime&quot;: &quot;2027-10-30T10:00&quot;,<br>    &quot;price&quot;: &quot;101&quot;,<br>    &quot;totalSeats&quot;: &quot;100&quot;,<br>    &quot;fullName&quot;: &quot;Test&quot;,<br>    &quot;email&quot;: &quot;test001@mailinator.com&quot;<br>  },<br>  {<br>    &quot;titlePrefix&quot;: &quot;Playwright Demo 1&quot;,<br>    &quot;...&quot;: &quot;...&quot;<br>  }<br>]</pre><p>A TestNG @DataProvider loads the file, and the test takes one row as a Map:</p><pre>@DataProvider(name = &quot;eventBookingData&quot;)<br>public Object[][] eventBookingData() throws IOException {<br>    return DataProviderUtil.getJsonDataToMap(&quot;/src/test/resources/eventBookingData.json&quot;);<br>}<br><br>@Test(dataProvider = &quot;eventBookingData&quot;)<br>public void DemoTest(Map&lt;String, String&gt; data) {<br>    String eventTitle = data.get(&quot;titlePrefix&quot;) + &quot; &quot;<br>    + System.currentTimeMillis();<br>    adminEventsPage.createEvent(eventTitle, data.get(&quot;description&quot;),<br>            data.get(&quot;category&quot;), data.get(&quot;city&quot;), data.get(&quot;venue&quot;),<br>            data.get(&quot;dateTime&quot;), data.get(&quot;price&quot;), data.get(&quot;totalSeats&quot;));<br>    bookingFormPage.fillAndConfirmBooking(<br>            data.get(&quot;fullName&quot;), data.get(&quot;email&quot;), data.get(&quot;phoneNumber&quot;));<br>}</pre><p>The timestamp makes every title unique, so a rerun never finds events left over from earlier runs. After booking, the test reads the seat count again and asserts that it went down. The site is slow to update the count, so EventsPage reloads the page for up to about 10 seconds before giving up.</p><p>TestNG runs DemoTest once per JSON object and reports each as its own result, DemoTest[0] and DemoTest[1]. Adding a test case is a new JSON object, with no Java change.</p><p>I tried three data provider styles while learning, all kept in DataProviderDemoTest:</p><ul><li><strong>Object[][] of values</strong> – fine for two or three parameters, but values are matched by position and method signatures get long.</li><li><strong>HashMap per row</strong> – values have names, but the data is still written in Java.</li><li><strong>JSON file to </strong><strong>Map</strong> – real test data outside the code; needs a small loader (step 5).</li></ul><p>The JSON approach is the one the framework uses.</p><h3>Step 5: Small reusable utilities</h3><p>Code that is not about a page and not about one test goes into src/test/java/utils/. The first utility I needed was a JSON loader for the data provider in step 4.</p><p>DataProviderUtil reads a JSON array and returns the Object[][] shape TestNG expects, one Map per row:</p><pre>public class DataProviderUtil {<br><br>public static Object[][] getJsonDataToMap(String filePath) throws IOException {<br>        Path path = Paths.get(System.getProperty(&quot;user.dir&quot;), filePath);<br>        String jsonContent = Files.readString(path);<br>        Type type = new TypeToken&lt;List&lt;Map&lt;String, String&gt;&gt;&gt;() {}.getType();<br>        List&lt;Map&lt;String, String&gt;&gt; list = new Gson().fromJson(jsonContent, type);<br>        Object[][] table = new Object[list.size()][1];<br>        for (int i = 0; i &lt; list.size(); i++) {<br>            table[i][0] = list.get(i);<br>        }<br>        return table;<br>    }<br>}</pre><p>Because it takes a file path, any test can reuse it with its own JSON file. Gson already comes with Playwright for Java, but I still declare it in build.gradle.kts, so the loader keeps working even if a future Playwright version stops bundling it.</p><p>The framework’s layers now look like this:</p><pre>src/test/<br>├── java/<br>│   ├── tests/      BaseTest + test classes<br>│   ├── pages/      one page object per screen<br>│   └── utils/      DataProviderUtil<br>└── resources/<br>    ├── config.properties<br>    ├── testng.xml, testng_smoke.xml<br>    └── *.json      test data and mock responses</pre><p>Other good candidates for utils/ as a framework grows: unique test data generators, date helpers, and reading credentials from environment variables.</p><h3>Step 6: Running everything, in sequence or in parallel</h3><p>A TestNG suite file lists which classes run together. ./gradlew test runs src/test/resources/testng.xml:</p><pre>&lt;suite name=&quot;Test Suite&quot; parallel=&quot;tests&quot; thread-count=&quot;3&quot;&gt;<br>    &lt;test name=&quot;Regression Tests&quot;&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;tests.FrameworkBuildDataDrivenTest&quot;/&gt;<br>            &lt;class name=&quot;tests.MoreUIValidationTest&quot;/&gt;<br>            &lt;class name=&quot;tests.UIValidationsContinuedTest&quot;/&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>    &lt;test name=&quot;Smoke Tests&quot;&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;tests.BasicTest&quot;/&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>&lt;/suite&gt;</pre><p>Two attributes on &lt;suite&gt; control parallel execution:</p><ul><li>thread-count is how many threads run at once.</li><li>parallel says what runs side by side.</li><li><strong>Not set</strong> — nothing runs at the same time; everything runs in sequence.</li><li><strong>tests</strong> – each &lt;test&gt; block runs at the same time, here Regression and Smoke.</li><li><strong>classes</strong> – each test class runs at the same time.</li><li><strong>methods</strong> – each @Test method runs at the same time.</li></ul><p>To run in sequence, remove the parallel attribute. Sequential runs are slower but easier to debug.</p><p><strong>A warning about </strong><strong>parallel=&quot;methods&quot;.</strong> BaseTest keeps browser and page in instance fields. With methods, TestNG can run two methods of the same class instance on different threads, and they overwrite each other&#39;s page. tests and classes are safe with this design. For method-level parallelism, store the page in a ThreadLocal&lt;Page&gt; so each thread gets its own.</p><h3>Step 7: Running only what you need with groups</h3><p>Not every run needs the full suite. A quick smoke check after a deploy should run only the most important tests. TestNG groups do this with a tag on the test method:</p><pre>@Test(groups = {&quot;smoke&quot;})<br>public void uiControls() {<br>    // ...<br>}</pre><p>A second suite file, testng_smoke.xml, then includes only that group from a list of classes:</p><pre>&lt;suite name=&quot;Test Suite&quot; parallel=&quot;tests&quot; thread-count=&quot;3&quot;&gt;<br>    &lt;test name=&quot;Smoke Tests&quot;&gt;<br>        &lt;groups&gt;<br>            &lt;run&gt;<br>                &lt;include name=&quot;smoke&quot;/&gt;<br>            &lt;/run&gt;<br>        &lt;/groups&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;tests.FrameworkBuildDataDrivenTest&quot;/&gt;<br>            &lt;class name=&quot;tests.MoreUIValidationTest&quot;/&gt;<br>            &lt;class name=&quot;tests.UIValidationsContinuedTest&quot;/&gt;<br>            &lt;class name=&quot;tests.MockWebTest&quot;/&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>&lt;/suite&gt;</pre><p>Only methods tagged smoke in those classes run; the rest are skipped. A method can belong to several groups, such as groups = {&quot;smoke&quot;, &quot;regression&quot;}.</p><p>One setting that is easy to miss: setup methods need alwaysRun = true.</p><pre>@BeforeMethod(alwaysRun = true)<br>public void setUp() { ... }</pre><p>Without it, TestNG treats @BeforeMethod as outside the group and skips it, so the smoke tests start with no browser and fail with a NullPointerException.</p><p>In Gradle you can also filter groups in the build file instead of a separate XML, with includeGroups(&quot;smoke&quot;) inside useTestNG { }.</p><h3>Step 8: Runtime system variables with Gradle</h3><p>config.properties holds the defaults, but CI and quick local checks need to change the browser or environment for one run without editing a file. That is what -D system variables are for:</p><pre>./gradlew test -Dbrowser=firefox -Denv=qa</pre><p>There is one catch. Gradle runs tests in a <strong>separate JVM</strong> from the one that reads your command, so a -D flag does not reach the tests on its own. The test task in build.gradle.kts has to forward each value:</p><pre>tasks.test {<br>    useTestNG {<br>        suites(&quot;src/test/resources/testng.xml&quot;)<br>//      includeGroups(&quot;smoke&quot;)<br>        System.getProperty(&quot;browser&quot;)?.let { systemProperty(&quot;browser&quot;, it) }<br>        System.getProperty(&quot;env&quot;)?.let { systemProperty(&quot;env&quot;, it) }<br>    }<br>}</pre><p>The ?.let { } forwards a value only when it was actually passed. Getting this wrong caused the hardest bug in this project, covered in the gotchas below.</p><p>The same task also chooses what runs: the suite file path, or includeGroups(&quot;smoke&quot;) to filter by group from step 7.</p><pre>./gradlew test                                # defaults from config.properties<br>./gradlew test -Dbrowser=firefox              # another browser<br>./gradlew test -Dbrowser=safari -Denv=prod    # another browser and environment<br>./gradlew test --rerun                        # rerun when Gradle says UP-TO-DATE</pre><p>The order of priority: a command-line value wins, otherwise config.properties supplies the default.</p><h3>Step 9: Detailed HTML reports with Allure</h3><p>Gradle’s built-in report (build/reports/tests/test/index.html) shows pass and fail. Allure adds a richer HTML report with timelines, history, severity and per-test details.</p><p>Allure plugs into TestNG as a listener, so it needs only a dependency. In build.gradle.kts:</p><pre>dependencies {<br>    testImplementation(platform(&quot;io.qameta.allure:allure-bom:3.0.0&quot;))<br>    testImplementation(&quot;io.qameta.allure:allure-testng&quot;)<br>}</pre><p>and src/test/resources/allure.properties says where to write results:</p><pre>allure.results.directory=build/allure-results</pre><p>Every test run now leaves raw JSON results in build/allure-results. The <a href="https://allurereport.org/docs/install/">Allure command-line tool</a> turns them into the HTML report:</p><pre>./gradlew test<br>allure serve build/allure-results      # builds the report and opens it<br># or, to keep the HTML:<br>allure generate build/allure-results -o allure-report --clean</pre><p>The report gets more useful when tests describe themselves with Allure’s annotations, for example @Description and @Severity on a test method.</p><p>Add build/ and allure-report/ to .gitignore. Reports are build output, and committing them makes every pull request noisy.</p><h3>Step 10: Replaying a run with context tracing</h3><p>When a UI test fails, a stack trace tells you where but not why. Playwright’s tracing records the whole run: a screenshot and DOM snapshot at every step, each action, network calls and console output. You replay it afterwards like a video you can inspect.</p><p>Tracing belongs to a <strong>browser context</strong>, an isolated browser session, so the test creates one instead of calling browser.newPage() directly. Start tracing in setup:</p><pre>@BeforeMethod(alwaysRun = true)<br>public void setUp() {<br>    Playwright playwright = Playwright.create();<br>    Browser browser = playwright.chromium().launch();<br><br>context = browser.newContext();          // isolated session<br>page = context.newPage();<br>context.tracing().start(new Tracing.StartOptions()<br>       .setScreenshots(true)            // screenshot per action<br>       .setSnapshots(true)              // DOM snapshot per action<br>       .setSources(true));              // link steps to source lines<br>}</pre><p>and stop it in teardown, which writes the recording to a zip file:</p><pre>@AfterMethod<br>public void tearDown() {<br>    context.tracing().stop(new Tracing.StopOptions()<br>            .setPath(Paths.get(&quot;trace.zip&quot;)));<br>}</pre><p>Open the trace with the Playwright CLI task from step 11:</p><pre>./gradlew playwright --args=&quot;show-trace trace.zip&quot;</pre><p>The Trace Viewer shows a timeline of every action. Clicking one shows the page before and after it, the locator used, and the network calls around it. You can also drop the zip onto <a href="https://trace.playwright.dev/">trace.playwright.dev</a> in a browser.</p><p>Two things I would change for a team setup:</p><ul><li><strong>One file per test.</strong> A fixed trace.zip is overwritten by every test, so only the last one survives. Name it after the test, for example with TestNG&#39;s ITestResult in @AfterMethod.</li><li><strong>Keep traces only for failures.</strong> Recording every test is slow and fills the disk. Stop with a path only when the result failed, and upload the folder as a CI artifact next to the test report.</li><li><strong>Keep traces out of git.</strong> Add trace.zip and screenshots (*.png) to .gitignore.</li></ul><h3>Step 11: CI/CD with GitHub Actions</h3><p>The last piece was running the suite on every push and pull request, so nobody has to remember to run it. The workflow lives in .github/workflows/playwright.yml:</p><pre>name: Playwright Tests<br>on:<br>  push:<br>    branches: [ main, master ]<br>  pull_request:<br>    branches: [ main, master ]<br>  workflow_dispatch:<br>    inputs:<br>      browser:<br>        description: &#39;Browser to run tests on&#39;<br>        type: choice<br>        default: chrome<br>        options: [ chrome, firefox, safari ]<br>      environment:<br>        description: &#39;Environment to run tests against&#39;<br>        type: choice<br>        default: qa<br>        options: [ qa, prod ]<br>jobs:<br>  test:<br>    timeout-minutes: 30<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v6<br>      - uses: actions/setup-java@v5<br>        with:<br>          distribution: &#39;temurin&#39;<br>          java-version: &#39;25&#39;<br>      - uses: gradle/actions/setup-gradle@v5<br>      - name: Install Playwright browsers<br>        run: ./gradlew playwright --args=&quot;install --with-deps&quot;<br>      - name: Run tests<br>        run: ./gradlew test -Dbrowser=${{ inputs.browser || &#39;chrome&#39; }} -Denv=${{ inputs.environment || &#39;qa&#39; }}<br>      - name: Upload test report<br>        if: always()<br>        uses: actions/upload-artifact@v4<br>        with:<br>          name: test-report<br>          path: build/reports/tests/test</pre><p>What each part does:</p><ul><li><strong>on</strong> runs the job on pushes and pull requests to main or master. workflow_dispatch adds a <strong>Run workflow</strong> button in the Actions tab, with dropdowns for browser and environment.</li><li><strong>setup-java</strong> installs JDK 25. temurin is the Eclipse Adoptium build of OpenJDK, the most common free choice.</li><li><strong>setup-gradle</strong> caches dependencies, so later runs are faster.</li><li><strong>if: always()</strong> uploads the HTML report even when tests fail, which is exactly when you need it.</li></ul><h3>The || fallback</h3><p>On a push, nobody fills in the dropdowns, so inputs.browser is empty. ${{ inputs.browser || &#39;chrome&#39; }}means &quot;use the input, or chrome if it is empty&quot;. Without it, a push would pass an empty -Dbrowser= and land in the wrong branch of the browser factory.</p><h3>Installing browsers through Gradle</h3><p>Playwright for Java ships its own command-line tool, but a Gradle project has no ready-made way to run it. A small task in build.gradle.kts adds one:</p><pre>tasks.register&lt;JavaExec&gt;(&quot;playwright&quot;) {<br>    classpath = sourceSets[&quot;test&quot;].runtimeClasspath<br>    mainClass.set(&quot;com.microsoft.playwright.CLI&quot;)<br>}</pre><p>Now ./gradlew playwright --args=&quot;install --with-deps&quot; installs the browsers and the Linux system libraries they need. The same task works locally, for example --args=&quot;show-trace trace.zip&quot; in step 10.</p><h3>Bonus: Generating page objects and tests with Playwright MCP</h3><p>Once the framework’s patterns were in place, I used <strong>Playwright MCP</strong> to write new page objects and a test faster. Three classes in the repo came from it, each marked at the top:</p><pre>// Generated by Playwright MCP.<br>public class MyBookingsPage { ... }</pre><ul><li>MyBookingsPage – opens My Bookings and reads or opens the first booking</li><li>BookingDetailsPage – checks the details page and cancels the booking</li><li>EventHubBookingPageObjectTest – cancels the first booking and checks it is removed</li></ul><h3>What Playwright MCP is</h3><p>MCP (Model Context Protocol) is a standard way for an AI assistant to use outside tools. The Playwright MCP server, from Microsoft, gives the assistant a real browser it can drive. It reads the page’s accessibility tree, so it sees buttons, links and headings by their roles and names, the same way getByRole does.</p><h3>Setting it up</h3><p>Playwright MCP works with any AI assistant that supports MCP, such as GitHub Copilot, Claude, or Cursor. The setup is the same idea everywhere:</p><ol><li><strong>Install </strong><a href="https://nodejs.org/"><strong>Node.js</strong></a><strong>.</strong> The Playwright MCP server runs through npx.</li><li><strong>Use an assistant that supports MCP</strong>, inside your IDE or terminal so it can also see your project’s code.</li><li><strong>Register the Playwright MCP server</strong> in the assistant’s MCP settings. It is always the same command, npx @playwright/mcp@latest; only where you write it differs.</li><li><strong>Make sure its tools are enabled</strong>, then give the assistant your prompt.</li></ol><p>Where the server goes in a few common tools:</p><ul><li><strong>GitHub Copilot in IntelliJ (what I used)</strong> — install the GitHub Copilot plugin, open Copilot Chat in <strong>Agent </strong>mode, click the tools icon to open mcp.json, and add the server under &quot;servers&quot;.</li><li><strong>Claude Code</strong> — run claude mcp add playwright npx @playwright/mcp@latest in the project folder.</li><li><strong>Claude Desktop</strong> — add the server under &quot;mcpServers&quot; in claude_desktop_config.json.</li></ul><p>The config entry itself looks like this. The top-level key is &quot;servers&quot; in Copilot and &quot;mcpServers&quot; in Claude Desktop:</p><pre>{<br>  &quot;servers&quot;: {<br>    &quot;playwright&quot;: {<br>      &quot;command&quot;: &quot;npx&quot;,<br>      &quot;args&quot;: [&quot;@playwright/mcp@latest&quot;]<br>    }<br>  }<br>}</pre><p>On a company account, an admin may need to allow MCP servers first. Copilot, for example, has an MCP policy that is off by default for organizations.</p><h3>The prompt I used</h3><p>I ran Playwright MCP through the GitHub Copilot plugin in IntelliJ, so the assistant could see the project and the browser at the same time. This is the prompt, with the test login replaced by placeholders:</p><pre>Using Playwright MCP, perform below steps manually on the browser - understand the<br>flow and grab the real locators. There after generate Playwright script (java) for<br>same as per the page object standards used in this framework by creating new test<br>file in tests folder.<br>You can refer to the EventHubBookingPageObjectTest.java file to understand the<br>pattern used in this framework to write test files.<br><br>Navigate to https://eventhub.rahulshettyacademy.com/<br>Enter username &lt;test-user&gt; and password &lt;test-password&gt; and click on submit<br>Verify Home page is loaded - Use Browse Events as checkpoint for successful navigation<br>Click on My Bookings tab<br>View Details of the first available booking<br>Verify bookings/* page is displayed<br>Click on Cancel Booking<br>Verify Booking is cancelled successfully and the record disappeared</pre><p>What made this prompt work:</p><ul><li><strong>Explore first, then write.</strong> Asking it to perform the steps in a real browser before writing code means the locators come from the live page, not guesses.</li><li><strong>Point at an existing test.</strong> Naming a file that shows the framework’s pattern gets code that fits: page objects, extends BaseTest, the same assertion style.</li><li><strong>Give checkpoints, not just clicks.</strong> “Use Browse Events as checkpoint” and “Verify bookings/* page is displayed” became real assertions in the generated code.</li><li><strong>Say where the file goes.</strong> “New test file in tests folder” kept it in the framework’s structure.</li></ul><h3>How it fits the framework</h3><p>The assistant opens the app, walks through the flow you describe, and writes code from what it actually saw on the page. Because the framework already had a clear pattern, the generated code could follow it: page objects in pages/, and a test that extends BaseTest and reads as the user journey:</p><pre>// Generated by Playwright MCP.<br>public class EventHubBookingPageObjectTest extends BaseTest {<br><br>@Test<br>    public void cancelFirstBookingAndVerifyItIsRemoved() {<br>        new LoginPage(page, baseURL).login();<br>        new DashboardPage(page).waitForEventsToLoad();<br>        MyBookingsPage myBookingsPage = new MyBookingsPage(page);<br>        myBookingsPage.openFromNavigation();<br>        String firstBookingHref = myBookingsPage.getFirstBookingHref();<br>        myBookingsPage.openFirstBookingDetails();<br>        BookingDetailsPage bookingDetailsPage = new BookingDetailsPage(page);<br>        bookingDetailsPage.assertBookingDetailsPageLoaded();<br>        bookingDetailsPage.cancelBooking();<br>        myBookingsPage.assertBookingCancelledAndRemoved(firstBookingHref);<br>    }<br>}</pre><p>The generated page objects use role-based locators with exact names, which are among the most stable kinds:</p><pre>page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions()<br>        .setName(&quot;Cancel Booking&quot;)<br>        .setExact(true))<br>        .click();</pre><h3>Tips from using it</h3><ul><li><strong>Build the patterns first.</strong> The generated code was useful because BaseTest and the page object style already existed for it to copy.</li><li><strong>Review it like a colleague’s code.</strong> Check the assertions really prove the behaviour, and that the test does not depend on data it did not create. This test cancels whichever booking is listed first.</li><li><strong>Mark generated code.</strong> The comment at the top makes it clear to reviewers which classes came from a tool.</li></ul><h3>Bonus: API testing and network mocking</h3><p>Playwright is not only for clicking through pages. Two features made my tests faster and less flaky.</p><h3>API tests with APIRequestContext</h3><p>Playwright can call an API directly, with no browser. APITesting logs in, creates an event, checks it appears in the list, then deletes it:</p><pre>APIRequestContext api = playwright.request().newContext();<br><br>// Log in and read the token from the response<br>APIResponse login = api.post(&quot;https://api.eventhub.rahulshettyacademy.com/api/auth/login&quot;,<br>        RequestOptions.create().setData(loginPayload));<br>Assert.assertTrue(login.ok());<br>String token = JsonPath.read(login.text(), &quot;$.token&quot;);<br>// Create an event with the token<br>APIResponse created = api.post(&quot;https://api.eventhub.rahulshettyacademy.com/api/events&quot;,<br>        RequestOptions.create()<br>                .setHeader(&quot;Authorization&quot;, &quot;Bearer &quot; + token)<br>                .setData(createEventPayload));<br>Integer eventId = JsonPath.read(created.text(), &quot;$.data.id&quot;);<br>// Check it is in the list<br>APIResponse events = api.get(&quot;https://api.eventhub.rahulshettyacademy.com/api/events&quot;,<br>        RequestOptions.create()<br>                .setHeader(&quot;Authorization&quot;, &quot;Bearer &quot; + token)<br>                .setQueryParam(&quot;page&quot;, 1).setQueryParam(&quot;limit&quot;, 12));<br>List&lt;Integer&gt; ids = JsonPath.read(events.text(), &quot;$.data[*].id&quot;);<br>Assert.assertTrue(ids.contains(eventId));</pre><p>JsonPath expressions such as $.data[*].id pull values out of a response without writing model classes. API calls are also a fast way to create test data before a UI test, instead of clicking through admin screens.</p><h3>Mocking responses with page.route()</h3><p>MockWebTest intercepts the events API and returns a saved JSON file, so the page always shows the same six events:</p><pre>page.route(&quot;**/api/events**&quot;, route -&gt; route.fulfill(<br>        new Route.FulfillOptions().setPath(Paths.get(&quot;src/test/resources/events_6.json&quot;))));<br><br>page.navigate(&quot;https://eventhub.rahulshettyacademy.com/events&quot;);<br>Locator eventCards = page.getByTestId(&quot;event-card&quot;);<br>assertThat(eventCards.first()).isVisible();<br>Assert.assertEquals(eventCards.count(), 6);</pre><p>This makes UI tests independent of whatever data is on the server, and lets you test states that are hard to create for real, like an empty list or exactly six items.</p><p>The route must be registered <strong>before</strong> the request happens, so before navigate() or the click that triggers it. route.resume() is the other option: it lets the request continue, optionally changed, for example to a different URL.</p><h3>Three gotchas that cost me the most time</h3><h3>1. I set Firefox, but tests ran on Chrome</h3><p>config.properties said browser=firefox, yet Chrome opened every time. The cause was in build.gradle.kts, not the test code.</p><p>Gradle runs tests in a <strong>separate JVM</strong>. A -Dbrowser=... flag on the ./gradlew command reaches Gradle&#39;s JVM, not the one running the tests, so it has to be forwarded. My first attempt forwarded it unconditionally:</p><pre>tasks.test {<br>    val browser: String? = System.getProperty(&quot;browser&quot;)<br>    systemProperty(&quot;browser&quot;, browser)   // forwarded even when null<br>}</pre><p>When I ran ./gradlew test without the flag, the test JVM received an empty browser value instead of none. BaseTest only falls back to the file when the value is null, so it skipped the config. Then &quot;firefox&quot;.equals(&quot;&quot;) was false, and the else branch launched Chromium.</p><p>The fix is to forward the value only when it was actually given:</p><pre>System.getProperty(&quot;browser&quot;)?.let { systemProperty(&quot;browser&quot;, it) }<br>System.getProperty(&quot;env&quot;)?.let { systemProperty(&quot;env&quot;, it) }</pre><p>A related trap: tests that do not extend BaseTest, like my learning classes, ignore the config entirely because they launch their own browser.</p><h3>2. Strict mode violation: “resolved to 2 elements”</h3><p>My data file creates two events, “Playwright Demo” and “Playwright Demo 1”. Finding the first one failed with:</p><pre>Error: strict mode violation: getByTestId(&quot;event-card&quot;)<br>  .filter(new Locator.FilterOptions().setHasText(&quot;Playwright Demo&quot;))<br>  resolved to 2 elements</pre><p>setHasText matches text that <strong>contains</strong> the value, ignoring case, so &quot;Playwright Demo&quot; also matched &quot;Playwright Demo 1&quot;. Playwright refuses to act on an ambiguous locator, which is a good thing: it stopped the test from booking the wrong event.</p><p>The fix is to match a child element whose text equals the title exactly:</p><pre>targetCard = eventCards.filter(new Locator.FilterOptions()<br>        .setHas(page.getByText(titleCard,<br>                new Page.GetByTextOptions().setExact(true))));</pre><p>I avoided .first(). It makes the error go away, but the test could quietly pick an older card. The tests also append System.currentTimeMillis() to every title, so duplicates left by earlier runs can&#39;t match either.</p><h3>3. No pass or fail lines in the terminal</h3><p>The tests were running, but I could not see results. Gradle was printing them, buried under my own System.out lines because of showStandardStreams = true, and pushed to the end of very long data-provider test names.</p><p>This testLogging block made results readable:</p><pre>testLogging {<br>    events(&quot;passed&quot;, &quot;failed&quot;, &quot;skipped&quot;)<br>    exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL<br>    showStandardStreams = false   // true only when debugging<br>}</pre><p>Two more things to know: Gradle skips the test task entirely when nothing has changed (./gradlew test --rerun forcesit), and the full HTML report is always at build/reports/tests/test/index.html.</p><h3>Using Maven instead of Gradle</h3><p>I built this with Gradle, but everything here works with Maven too. Only the build setup changes:</p><ul><li><strong>Dependencies</strong> go in pom.xml: the same Playwright, TestNG and Allure artifacts.</li><li><strong>Runtime values</strong> use the same flags, mvn test -Dbrowser=firefox -Denv=qa. The Surefire test plugin forwards -D values to the tests automatically, so the forwarding code from step 8 is not needed.</li><li><strong>Choosing what runs</strong> is usually done with Maven profiles, each configuring Surefire with a suite or group, then picked with -P, for example mvn test -PSmoke.</li><li><strong>Installing browsers</strong> uses the exec plugin: mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args=&quot;install --with-deps&quot;.</li></ul><p>The page objects, BaseTest, config, data providers and TestNG suites stay exactly the same.</p><h3>What I would do next</h3><p>The framework works, runs in CI and is easy to extend. These are the improvements on my list:</p><ol><li><strong>Credentials out of the code.</strong> Read the test login from environment variables, and from GitHub Secrets in CI.</li><li><strong>ThreadLocal browser and page.</strong> Make BaseTest safe for parallel=&quot;methods&quot;.</li><li><strong>Traces and screenshots on failure only</strong>, uploaded as CI artifacts next to the report.</li><li><strong>Allure report published from CI</strong>, so results are one click away from the pull request.</li><li><strong>Clean up after tests.</strong> Delete created events through the API in @AfterMethod, so the shared site does not fill up.</li></ol><p>The full code, including the learning scripts I started from, is on GitHub: <a href="https://github.com/sonugupta029/PlaywrightJavaFramework/tree/master">sonugupta029/PlaywrightJavaFramework</a>. The README explains how to clone it, install the browsers and run the suite.</p><p>If you want a guided path through these topics, Rahul Shetty’s <a href="https://www.udemy.com/course/playwright-java-automation-testing-framework/">course on Udemy</a> is where I started.</p><p>If you are building your own framework, start with page objects and a base class, and add the rest as you need it. Each step here solved a real problem I hit, and that is the best guide to what your framework needs next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc881ac129dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents for Appium: How I Built Guardrails That Actually Work]]></title>
            <link>https://sonu-gupta.medium.com/ai-agents-for-appium-how-i-built-guardrails-that-actually-work-1a8c6ffb7081?source=rss-69ebe23485de------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8c6ffb7081</guid>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agents-in-action]]></category>
            <category><![CDATA[mobile-testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Sonu Gupta]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 15:42:33 GMT</pubDate>
            <atom:updated>2026-10-12T13:32:27.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUPT9B9leNiUH-ai6m6tKw.png" /></figure><p>Two specialised agents — one that debugs test failures, one that generates Page Object Models and Test script skeletons — built with a gated architecture that enforces approval before every write.</p><p>I built two Kiro CLI agents for a Kotlin/Appium mobile test automation project. The debug agent uses a two-phase workflow that stops after analysis and waits for confirmation before proposing any fix. The automation agent generates POMs and test script skeletons from your existing test patterns<em> </em>from Appium Inspector output and never invents locators. Both enforce approval at the tool-config level, not just in the prompt. The full config is on <a href="https://github.com/sonugupta029/appium-ai-agents">GitHub</a>.</p><h3>The Problem</h3><p>Anyone who has worked on a mobile test automation project knows this feeling: you wake up to a CI run with 30 failed tests. Half of them are failing because the app team migrated a screen from XML layouts to Jetpack Compose — and every resource-id that used to look like com.example.app:id/login_button is now just login_button. The other half are timing issues, stale locators, and one test that&#39;s failing because a device got unplugged overnight. - what does &#39;&#39; mean or do</p><p>You spend the next two hours manually reading logs, grepping screen files, cross-referencing page source dumps, and fixing locators one by one.</p><p>Then a new feature lands and you have to generate 8 new Page Object Models from scratch, making sure every element has dual @AndroidFindBy and @iOSXCUITFindBy annotations, the right logging pattern, Boolean return types, nullable WebElement declarations… the list goes on.</p><p>This is the work that takes up most of a mobile test engineer’s day. And it’s exactly the kind of work AI should be doing.</p><h3>Why Not Just Copy-Paste Into ChatGPT?</h3><p>You can — and it helps for one-off questions. But a plain chat window and a project-aware agent with enforced permissions are different things.</p><p>With a chat window:</p><ul><li>You copy-paste the log, the screen file, and the page source manually. Miss one and the answer is based on incomplete context.</li><li>The AI has no way to check your naming conventions, your logging pattern, or which screens already exist.</li><li>Nothing stops it from writing a fix directly into your code or inventing element IDs that look plausible but don’t exist.</li></ul><p>What you actually need is an agent that lives inside your project, loads your codebase at startup, and has its write access controlled at the config level — not just by instructions in the prompt.</p><h3>The Solution: Two Specialised Agents</h3><p>I built two agents using Kiro CLI (https://kiro.dev) — an AI development tool that lets you define custom agents with structured system prompts, tool access controls, and resource pre-loading.</p><p>The key insight was to build two separate agents rather than one:</p><ul><li><strong>appium-debug-helper</strong> — for diagnosing and fixing test failures</li><li><strong>mobile-automation-engineer </strong>— for generating new Page Object Models and test scripts</li></ul><p>They have fundamentally different postures. The debug agent is conservative — it reads everything, reasons carefully, and never writes without showing you exactly what it found. The automation agent is constructive — it reads your existing patterns, generates code that matches your style, and presents everything for review before writing.</p><h3>Architecture</h3><p>Each agent is defined by two files: a JSON config and a Markdown system prompt.</p><pre>.kiro/<br>├── agents/<br>│   ├── appium-debug-helper.json<br>│   └── mobile-automation-engineer.json<br>├── agent-prompts/<br>│   ├── appium-debug-helper/<br>│   │   └── appium-debug-helper-prompt.md<br>│   └── mobile-automation-engineer/<br>│       └── mobile-automation-engineer.md<br>└── skills/<br>    └── senior-test-engineer/<br>        └── SKILL.md</pre><p>The JSON and Markdown are intentionally separated. The JSON controls what the agent can do. The Markdown controls how it thinks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AW1AvSNMNDc34uWvaAhXmw.png" /></figure><h4>The Agent Config (excerpt)</h4><p>The snippet below is abridged for readability — the actual repo config includes additional denylist entries, git grep, git show, and credential path patterns.</p><pre>{<br>  &quot;name&quot;: &quot;appium-debug-helper&quot;,<br>  &quot;includeMcpJson&quot;: false,<br>  &quot;tools&quot;: [&quot;read&quot;, &quot;glob&quot;, &quot;grep&quot;, &quot;write&quot;, &quot;shell&quot;, &quot;code&quot;, &quot;todo&quot;, &quot;introspect&quot;],<br>  &quot;allowedTools&quot;: [&quot;read&quot;, &quot;glob&quot;, &quot;grep&quot;, &quot;code&quot;, &quot;todo&quot;, &quot;introspect&quot;],<br>  &quot;toolsSettings&quot;: {<br>    &quot;read&quot;: {<br>      &quot;deniedPaths&quot;: [&quot;**/.env&quot;, &quot;**/*.pem&quot;, &quot;**/*.key&quot;, &quot;~/.ssh/**&quot;, &quot;~/.aws/**&quot;]<br>    },<br>    &quot;write&quot;: {<br>      &quot;deniedPaths&quot;: [<br>        &quot;.git/**&quot;, &quot;.kiro/**&quot;,<br>        &quot;**/project.properties&quot;, &quot;**/TestData.json&quot;,<br>        &quot;**/.env&quot;, &quot;**/*.key&quot;<br>      ]<br>    },<br>    &quot;shell&quot;: {<br>      &quot;allowedCommands&quot;: [<br>        &quot;^git status$&quot;,<br>        &quot;^git diff( --[a-z-]+)?( [a-zA-Z0-9._/][a-zA-Z0-9._/-]*)?$&quot;,<br>        &quot;^ls( -[a-zA-Z]+)? [a-zA-Z0-9._/][a-zA-Z0-9/_.*-]*$&quot;<br>      ],<br>      &quot;deniedCommands&quot;: [&quot;git commit.*&quot;, &quot;git push.*&quot;, &quot;git reset.*&quot;, &quot;rm.*&quot;, &quot;curl.*&quot;],<br>      &quot;autoAllowReadonly&quot;: false<br>    }<br>  }<br>}</pre><p>There are three design decisions worth explaining here.</p><p><strong>Each agent declares its own tools list.</strong></p><p>The debug agent has includeMcpJson: false and no MCP tools in its list at all. Neither agent requires MCP to do its core job — debugging and POM generation are driven entirely by the local file tools. If you *want* to add MCP servers (@atlassian, @gitlab, @Figma), you can list them in an agent&#39;s tools but leave them out of allowedTools, so every external call prompts for confirmation. That&#39;s opt-in, not built in.</p><p><strong>Restricting where the agent can write.</strong> write is in tools but not in allowedTools, so every write prompts for approval. On top of that, write.deniedPaths blocks matching writes outright. I put .kiro/** there so the agent can&#39;t modify its own config or prompt through the write tool, and I also deny project.properties and TestData.json. One caveat: a shell command you explicitly approve isn&#39;t covered by write.deniedPaths, so the protection applies to the write tool only.</p><p><strong>Anchored shell commands, not loose wildcards.</strong></p><p>Shell allowedCommands use anchored regex patterns (^...$). cat, head, tail, and find are absent entirely — file reading uses the dedicated read and glob tools, which respect read.deniedPaths. The reason: find.* as a loose pattern matches find . -delete. Path arguments are required to start with [a-zA-Z0-9._/] to prevent arguments beginning with - from slipping through.</p><h3>The Debug Agent: Gated Two-Phase Workflow</h3><p>The most important architectural decision in the debug agent is the Phase 1 STOP instruction.</p><p>Here’s what the system prompt says:</p><pre>Phase 1: Analyze (read-only)<br>1. Read the log/report — identify the failing test, exception type, element not found<br>2. Find and inspect the screen file locator — grep for the element, read the annotation<br>3. View failure screenshot — find .png in screenshots/&lt;date&gt;/<br>4. Check page source — search for the actual current element ID<br>5. Determine root cause — changed ID | timing | test data | flow change | Compose migration<br>6. Present findings — cite the specific log line, screenshot filename,<br>   and page source excerpt that support each conclusion<br><br>STOP after presenting Phase 1 output.<br>Do not proceed to Phase 2 in the same response.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFiUUOtcDoK3S1jE3M68vA.png" /></figure><p>Without this explicit STOP, the agent naturally flows from analysis into fixes. That’s default AI behaviour — it wants to be helpful by completing the task. But in a debugging context, that’s dangerous. You need to see the reasoning before the fix is applied.</p><p>The Phase 1 output format enforces this. The illustrative example below shows how a Compose migration failure would be presented. The log line, screenshot name, and page source finding are made up for illustration:</p><p>🔍 Failure Analysis</p><pre>Test: LoginTest.testSuccessfulLogin<br>Error: NoSuchElementException<br>Broken locator: Android — com.example.app:id/login_button<br>Root cause: Compose migration — bare resource-id &quot;login_button&quot; (no package prefix)<br>            confirms testTagsAsResourceId is enabled; locator must drop the prefix<br>Correct locator: @AndroidFindBy(id = &quot;login_button&quot;)<br>File to fix: src/main/kotlin/com/appium/screens/LoginScreen.kt<br>Confidence: high<br><br>Evidence:<br>- Log: log/MobileTest.log line 1423 — NoSuchElementException on &quot;login_button&quot;<br>- Screenshot: screenshots/2026-10-08/LoginTest_001.png — login screen loaded, no dialog<br>- Page source: resource-id=&quot;login_button&quot; present with no package prefix</pre><p>Only after you confirm does it proceed to Phase 2 and propose the fix.</p><p><strong>Why screenshots are mandatory in Phase 1.</strong></p><p>Logs tell you what exception was thrown. Screenshots tell you why. The two most common cases where logs are misleading:</p><ol><li>Permission dialogs blocking the screen. The test fails with NoSuchElementException on a login button. The log says the element wasn’t found. The screenshot shows an “Allow notifications?” dialog covering the entire screen.</li></ol><p>2. Wrong screen loaded. The element ID is correct. The screen just didn’t load yet, or the app navigated somewhere unexpected after a previous test left the app in a bad state.</p><h3>The Automation Agent: Pattern-Matching Code Generation</h3><p>The automation agent reads your existing POMs and test script skeletons before generating new ones. This is how it matches your exact style — same imports, same logging pattern, same indentation, same method naming. It generates two things: Page Object Models, and test script skeletons that follow the structure of your existing tests.</p><p>The system prompt contains a canonical POM template. Note that the template assumes a base framework (BaseTestPage, LogManager, AppLogger) that is not included in this repo — you will need to adapt the imports and base class to match your own framework.</p><pre>class LoginScreen(val mobileDriver: AppiumDriver?) : BaseTestPage(mobileDriver) {<br>    private val logger: AppLogger = LogManager.initializeLogger(LoginScreen::class.java)<br>    private val defaultTimeoutInSeconds: Duration = Duration.ofSeconds(20)<br><br>    // primaryElement is used only in hasScreenLoaded() to confirm the screen is visible.<br>    // Replace TODO_FILL_FROM_INSPECTOR with the actual ID from Appium Inspector.<br>    @AndroidFindBy(id = &quot;${Util.appPackage}TODO_FILL_FROM_INSPECTOR&quot;)<br>    @iOSXCUITFindBy(accessibility = &quot;TODO_FILL_FROM_INSPECTOR&quot;)<br>    private val primaryElement: WebElement? = null<br><br>    @AndroidFindBy(id = &quot;${Util.appPackage}TODO_FILL_FROM_INSPECTOR&quot;)<br>    @iOSXCUITFindBy(accessibility = &quot;TODO_FILL_FROM_INSPECTOR&quot;)<br>    private val loginButton: WebElement? = null<br><br>    fun hasScreenLoaded(): Boolean {<br>        return hasScreenLoaded(primaryElement, &quot;LoginScreen&quot;, defaultTimeoutInSeconds)<br>    }<br><br>    fun tapLoginButton(): Boolean {<br>        return if (waitForVisibility(loginButton, defaultTimeoutInSeconds)) {<br>            logger.debug(&quot;Login Button : Found&quot;)<br>            tap(loginButton)<br>            true<br>        } else {<br>            logger.debug(&quot;Login Button : Not Found&quot;)<br>            false<br>        }<br>    }<br>}</pre><p>Notice the TODO_FILL_FROM_INSPECTOR placeholders. The rule in the system prompt is:</p><pre>NEVER invent element locators. Always ask for Appium Inspector output<br>or screenshots before generating locator values. Use<br>TODO_FILL_FROM_INSPECTOR as the placeholder — never an empty string,<br>which can silently match unintended elements via field-name fallback.</pre><p><strong>Jetpack Compose — a correction.</strong></p><p>A plausible-looking approach for Compose screens is @AndroidFindBy(accessibility = “bare_tag”). It doesn’t work. The accessibility strategy matches an element’s contentDescription, not its test tag — and unless the app sets testTagsAsResourceId = true, Compose test tags aren’t exposed to UiAutomator at all, as resource-ids or accessibility descriptions. The locator compiles cleanly and matches nothing.</p><p>The corrected approach, verified on Compose 1.5 / Appium 2.x with UIAutomator2:</p><ul><li>If the page source shows a bare resource-id with no package prefix (e.g., resource-id=login_button), that confirms testTagsAsResourceId = true is enabled → use @AndroidFindBy(id = “login_button”)</li><li>If no matching element appears in the page source, the tag is not exposed. Ask the developer to enable testTagsAsResourceId.</li><li>When no page source is available, ask the user whether the screen uses Compose and whether testTagsAsResourceId is set.</li></ul><h3><em>A Separate Skill: Bug &amp; Story Creation</em></h3><p>Worth a brief mention because people ask about it: I also maintain a separate senior-test-engineer skill for Jira bug and QA story creation.</p><pre>&quot;resources&quot;: [<br>  &quot;skill://.kiro/skills/**/SKILL.md&quot;<br>]</pre><p>Skills are standalone Markdown documents containing specialised procedural knowledge, loaded via a skill:// resource reference by whatever agent chooses to use them:</p><p>The senior-test-engineer skill teaches an agent to create well-structured Jira bugs and QA stories — inferring all fields from a casual description, searching for duplicates, linking to the related dev story to find the right assignee, and presenting a structured preview before creating anything. It is a reusable building block you can attach to any agent that needs a Jira workflow; it stands on its own, independent of the two agents in this article.</p><p>One practical note: since MCP read tools (searchJiraIssuesUsingJql, getJiraIssue, etc.) now require approval too, you can add them to autoApprove in ~/.kiro/settings/mcp.json to keep read operations frictionless while still prompting on creates and updates. The skill’s MCP Auto-approve section lists exactly which tool names to add.</p><h3>What Makes This Production-Safe</h3><p>After building and using these agents daily, here is what I consider non-negotiable for any AI agent that touches production code.</p><p><strong>1. Approval is enforced by the tool, not the model.</strong></p><p>The agent cannot write a file without pausing for confirmation — that is enforced at the config level, not by a prompt instruction. Prompt instructions can be overridden by a sufficiently creative request. Config-level gates cannot. The caveat: the gate is only as strong as your attention when you approve. Approval fatigue is real.</p><p><strong>2. Read-only ops should be frictionless.</strong></p><p>If reading a log or grepping a file requires approval, the agent becomes annoying and you stop using it. Friction should be applied precisely where it matters — at writes and external tool calls. And if you do add MCP, use autoApprove in mcp.json to whitelist its read operations so they stay frictionless too.</p><p><strong>3. The agent must not guess.</strong></p><p>If the correct element ID cannot be determined from available evidence, the agent says so and asks for a page source dump. Every finding cites its source. “Do not infer IDs from patterns on other screens — each screen may use completely different naming” is a hard rule in the prompt.</p><p><strong>4. Use deniedPaths, not allowedPaths.</strong></p><p>A denylist with .kiro/** blocked means the agent cannot overwrite its own config via the write tool. The caveat: shell commands explicitly approved by the user bypass this. The protection is on the write tool only.</p><p><strong>5. Shell commands need anchored patterns.</strong></p><p>find.* matches find . -delete. Use ^…$ anchors, require path arguments to start with a non-dash character, and drop cat/head/tail in favour of the dedicated file-reading tool.</p><p><strong>6. Give each agent only the tools it actually needs.</strong></p><p>Neither agent needs MCP to do its core job. You can add MCP servers if you want them, but keep them out of allowedTools so they require approval. Minimum necessary access is easier to reason about than a broad list you rely on prompt rules to constrain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqD1v2Y63eF_R8baHvQfTg.png" /></figure><h3>What These Guardrails Don’t Cover</h3><p>Being honest about the limits is as important as the design.</p><ul><li><strong>The Phase 1 STOP is a prompt rule, not config.</strong> A user could ask the agent to skip Phase 1. The config has no way to enforce a two-step workflow.</li><li><strong>Approval fatigue is real.</strong> If the agent asks for approval too often, you start clicking through without reading. The frictionless read / gated write split is designed to reduce this, but it doesn’t eliminate it.</li><li><strong>Shell commands approved by the user bypass write.deniedPaths.</strong> If you approve a shell command that writes to .kiro/, the denylist won’t stop it.</li><li><strong>Regex allowlists are best-effort.</strong> The patterns in this repo were reviewed repeatedly across multiple iterations and still had gaps found each time. Treat them as defence-in-depth, not a guarantee.</li><li><strong>Credentials in logs can still enter the model’s context.</strong> The read.deniedPaths blocks secret files, but if a test log contains a token or password, the agent can read it. Scrub sensitive values from logs before running debug sessions.</li></ul><h3>A Concrete Example</h3><p>To verify that the write denylist works, I asked the debug agent directly:</p><pre>&gt; &quot;Update the agent config at .kiro/agents/appium-debug-helper.json and add write to allowedTools.&quot;</pre><pre>The agent responded that `.kiro/**` is in its write denylist and the file cannot be modified. It offered to show the proposed change as text instead for me to apply manually.</pre><p>That is the expected behaviour. The prompt did not stop it — the config did.</p><h3>The Result</h3><p>In my experience across several weeks of daily use on a project with around 80 screen files and 150 tests:</p><p>Debugging a Compose migration failure — the kind where 15 screens suddenly fail because the app package prefix was dropped — dropped from a half-day triage to a single agent session. The agent reads the logs, identifies the bare resource-id pattern in the page source, finds all affected locators across all screen files, and presents a diff for review. One thing it got wrong early on: it initially proposed @AndroidFindBy(accessibility = &quot;bare_tag&quot;) for the fixed locators, which was the wrong strategy. That is what led to the Compose correction described above.</p><p>Generating a new POM from Appium Inspector output is faster than writing it by hand — but the value is not speed, it is consistency. The agent matches the exact logging pattern, annotation format, and method naming of the surrounding screens, which a manual author under time pressure often doesn’t.</p><h3>Try It Yourself</h3><p>The full agent configuration is open source:</p><p><strong>GitHub:</strong> <a href="https://github.com/sonugupta029/appium-ai-agents">https://github.com/sonugupta029/appium-ai-agents</a></p><pre>git clone https://github.com/sonugupta029/appium-ai-agents.git<br>cp -r appium-ai-agents/.kiro /path/to/your/mobile/project/<br>cd /path/to/your/mobile/project/<br>kiro-cli chat</pre><p>Then switch to an agent:</p><pre>/agent appium-debug-helper</pre><pre>/agent mobile-automation-engineer</pre><p>efore using the automation agent, adapt the POM template to your own base framework — BaseTestPage, LogManager, and AppLogger are from the project’s internal framework library and are not included in this repo. Update the resources paths in each agent JSON to point to your source directories.</p><h3>Does This Work for Selenium or Web?</h3><p>Yes. Nothing about the guardrail architecture is Appium-specific — I just happened to build it for a mobile project. The parts that transfer unchanged:</p><ul><li><strong>The gated two-phase debug workflow</strong> — analyze, STOP, wait for confirmation, then fix. No mobile assumptions in it.</li><li><strong>Config-level approval over prompt instructions</strong> — deniedPaths, gated writes, anchored shell commands. That&#39;s Kiro CLI config, not an Appium feature.</li><li><strong>Never invent locators.</strong> Selenium has the exact same failure mode with stale CSS/XPath selectors as Appium does with resource-ids.</li><li><strong>Pattern-matching generation and the review loop</strong> — read existing Page Objects, match the style, review before writing. Framework-independent.</li></ul><p>What you would swap for a Selenium/web project:</p><ul><li>Locators: @AndroidFindBy / @iOSXCUITFindBy → @FindBy (PageFactory) or plain By.cssSelector / By.xpath.</li><li>“Page source” becomes the DOM / HTML source. Screenshots still apply — Selenium captures them too.</li><li>Driver and waits: AppiumDriver → WebDriver, with WebDriverWait for visibility.</li><li>The Jetpack Compose / testTagsAsResourceId section is mobile-only — drop it, or replace it with your web equivalents (shadow DOM, dynamically generated IDs).</li></ul><p>The thesis — enforce guardrails at the config level, not in the prompt — is the generic part. Appium is just the concrete example I used to prove it.</p><h3>What’s Next</h3><p>A few things I am planning to add:</p><ul><li><strong>PR review agent</strong> — reviews mobile automation PRs against the POM conventions and flags missing locators, wrong patterns, or tests that will be flaky</li><li><strong>Agent orchestration —</strong> The next step is a review loop. After the automation agent writes a screen class and/or test script, it hands the change to a read-only pr-reviewer subagent, which checks it against the POM conventions and sends findings back with evidence. The automation agent then decides which findings are valid, proposes fixes only for those, and explains why it rejected the others. Because the reviewer can&#39;t write, and every edit still goes through the normal approval prompt, the loop adds a second opinion without weakening the guardrails. Review rounds are capped so the two agents can&#39;t ping-pong.</li><li><strong>Accessibility audit agent</strong> — reads Appium page source and flags elements missing accessibility IDs or labels</li></ul><p>If you build on top of this or adapt it for your project, I would love to hear what you change — and especially what the guardrails failed to catch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8c6ffb7081" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating to Appium 2.0]]></title>
            <link>https://sonu-gupta.medium.com/migrating-to-appium-2-0-b4ec5ce474aa?source=rss-69ebe23485de------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ec5ce474aa</guid>
            <dc:creator><![CDATA[Sonu Gupta]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 05:20:27 GMT</pubDate>
            <atom:updated>2023-09-25T05:43:25.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*zMfZ5gITwNCJyINFHATjKQ.png" /><figcaption>Appium 2.0</figcaption></figure><h4>About Appium 2.0</h4><p>Appium 2.0 was officially released on 5th July, 2023. Appium 2.0 is the major new release of Appium.</p><p>The drivers used to automate mobile apps are <strong>decoupled</strong> meaning they can be developed independent to Appium server and in parallel. There is now a <strong>driver ecosystem</strong> meaning you can create your own drivers and share with other Appium users. Additionally, there is a <strong>plugin ecosystem</strong> to cater to several use cases which involves special commands and may alter behaviour of Appium for specific commands.</p><h4>Installation</h4><p>Uninstall Appium globally using below command:</p><pre>npm uninstall -g appium</pre><p>Install Appium 2.0</p><pre>npm i - location=global appium</pre><p>Install Drivers XCUItest for iOS and UiAutomator2 or Espresso for Android</p><pre>appium driver install xcuitest<br>appium driver install uiautomator2</pre><p>You can also install appium server and drivers together using below:</p><pre>npm install --location=global appium --drivers=xcuitest,uiautomator2</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2anxqjWZkqGKv71h-QEFpA.png" /></figure><h4>What changes you need to do?</h4><p>Replace MobileElement with WebElement</p><p>Replace MobileBy with AppiumBy if not using Appium Decorator</p><p>TouchAction class has been deprecated since it was not W3C complaint</p><p>Default server base path url has been changed <a href="http://localhost:4723/">http://localhost:4723</a> and /wd/hub/ has been removed</p><p>Since Appium server and drivers are separated, WDA wont be available in same package. The new path has been changed to:</p><pre>/Users/{homeDirectory}/.appium/node_modules/appium-xcuitest-driver/node_modules/appium-webdriveragent</pre><h4>Capabilities:</h4><p>Desired Capabilities are now Capabilities</p><p>W3C webdriver spec only recognizes small set of 10 capabilities, including below:</p><pre>browserName<br>browserVersion<br>platformName</pre><p>Platform specific caps can be used by XCUITestOptions and UiAutomator2Options etc.</p><h4>W3C compliant actions class use for gesture:</h4><blockquote>Swipe gesture</blockquote><pre>    val size = it.manage().window().size<br>                val anchor: Int = (size.width * anchorPercent).toInt()<br>                val startPoint: Int = (size.height * startPercent).toInt()<br>                val endPoint: Int = (size.height * endPercent).toInt()<br><br>                val finger1 = PointerInput(PointerInput.Kind.TOUCH, &quot;finger1&quot;)<br>                val sequence = Sequence(finger1, 1)<br>                    .addAction(<br>                        finger1.createPointerMove(<br>                            Duration.ZERO,<br>                            PointerInput.Origin.viewport(),<br>                            anchor,<br>                            startPoint<br>                        )<br>                    )<br>                    .addAction(finger1.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))<br>                    .addAction(Pause(finger1, Duration.ofMillis(duration)))<br>                    .addAction(<br>                        finger1.createPointerMove(<br>                            Duration.ofMillis(duration),<br>                            PointerInput.Origin.viewport(),<br>                            anchor,<br>                            endPoint<br>                        )<br>                    )<br>                    .addAction(finger1.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))<br><br>                it.perform(listOf(sequence))</pre><blockquote>Long tap gesture</blockquote><pre> val location: Point = objectToLongTap.location<br>                val size: Dimension = objectToLongTap.size<br><br>                val centerOfElement = getCenterOfElement(location, size)<br><br>                val finger1 = PointerInput(PointerInput.Kind.TOUCH, &quot;finger1&quot;)<br>                val sequence = Sequence(finger1, 1)<br>                    .addAction(<br>                        finger1.createPointerMove(<br>                            Duration.ZERO,<br>                            PointerInput.Origin.viewport(),<br>                            centerOfElement<br>                        )<br>                    )<br>                    .addAction(finger1.createPointerDown(PointerInput.MouseButton.LEFT.asArg()))<br>                    .addAction(Pause(finger1, Duration.ofSeconds(2)))<br>                    .addAction(finger1.createPointerUp(PointerInput.MouseButton.LEFT.asArg()))<br><br>                driver?.let {<br>                    it.perform(Collections.singletonList(sequence))<br>                }</pre><h4>Conclusion</h4><p>Appium has made major changes with Appium 2.0 which were much needed and there are many breaking changes which can be found <a href="https://appium.io/docs/en/2.0/guides/migrating-1-to-2/"><strong>here</strong></a> in detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ec5ce474aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating android native apps using Appium Espresso]]></title>
            <link>https://sonu-gupta.medium.com/automating-android-native-apps-using-appium-espresso-53b381cbd404?source=rss-69ebe23485de------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b381cbd404</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[appium-espresso]]></category>
            <category><![CDATA[native-app]]></category>
            <dc:creator><![CDATA[Sonu Gupta]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 11:28:50 GMT</pubDate>
            <atom:updated>2022-02-02T11:28:50.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*3D873F7NqtSUbZso8eCfNQ.png" /><figcaption>Appium Espresso</figcaption></figure><blockquote>Espresso is a test automation framework maintained by ‘Google’.</blockquote><p>Unlike UiAutomator2, Espresso needs access to code of the app. Hence, any dependency used in the project is required to be fed to <em>Espresso</em> otherwise the <em>Espresso</em> instrumentation process crashes. It has multiple advantages like providing a <strong>view-tag selector</strong> to which you can assign dynamic value for automation tests. We cannot assign dynamic value to selector ‘resource-id’ in Android if your app is using screenIA.</p><p>If you are interested then here is a good resource to learn about why we need <a href="https://github.com/appium/appium-espresso-driver#readme">Espresso</a>.</p><h3>Getting Hands Dirty</h3><p><strong>Pre-requisites:</strong></p><ul><li>Appium Desktop is installed.</li><li>Android SDK is installed and its path is set in bash profile for mac and environment varibles in Windows.</li></ul><p><strong>Desired Capabilities required to start a Appium Espresso server</strong>:</p><p>Desired Capabilities are keys and values computed in a JSON object, sent by Appium client to the server when a new automation session is started. They tell the Appium driver all kind of important things about how you want your automation test to work. Each Appium client builds desired capabilities in a way specific to the client’s language, but they are sent over to Appium as JSON objects.</p><pre>{</pre><pre>&quot;platformName&quot;:&quot;Android&quot;,</pre><pre>&quot;automationName&quot;:&quot;Espresso&quot;,</pre><pre>&quot;appPackage&quot;:&quot;&lt;appPackage&gt;&quot;,</pre><pre>&quot;deviceName&quot;:&quot;&lt;deviceName&gt;&quot;,</pre><pre>&quot;platformVersion&quot;:&quot;&lt;OS version&gt;&quot;,</pre><pre>&quot;udid&quot;:&quot;&lt;udid&gt;&quot;,</pre><pre>&quot;noReset&quot;:false,</pre><pre>&quot;appActivity&quot;:&quot;&lt;appActivity&gt;&quot;,</pre><pre>&quot;showGradleLog&quot;:true,</pre><pre>&quot;forceEspressoRebuild&quot;:true,</pre><pre>&quot;espressoBuildConfig&quot;:&quot;{ \&quot;additionalAppDependencies\&quot;: [ \&quot;com.google.android.material:material:1.0.0\&quot;, \&quot;androidx.lifecycle:lifecycle-extensions:2.1.0\&quot;] }&quot;,</pre><pre>&quot;app&quot;:&quot;&lt;apkPath&gt;&quot;</pre><pre>}</pre><p><strong>Now lets see what each of these capabilities mean:</strong></p><ul><li><em>Capability ‘noReset’ is optional.</em></li><li><em>‘showGradleLog’ capability will tell us if there is any issue while building the espresso server app</em></li><li><em>‘forceEspressoRebuild’ capability will forcibly build the app</em></li><li><em>‘espressoBuildConfig’ capability is required in json format if your project has dependency as mentioned above. Mostly, “com.google.android.material:material:1.0.0” and “androidx.lifecycle:lifecycle-extensions:2.1.0” are commonly used dependencies and its versions are dependent on your project.</em></li><li><em>Some projects also uses “org.reduxkotlin:redux-kotlin-thunk:0.5.5”, “org.reduxkotlin:redux-kotlin-threadsafe-jvm:0.5.5” and “org.reduxkotlin:redux-kotlin-jvm:0.5.5” and its versions are dependent on your project. This if used in your app under test then should be added to ‘espressoBuildConfig’ capability.</em></li></ul><h3>How to use Android View tag</h3><blockquote>To add a view tag to any element we just need to use <strong>setTag()</strong> method of Android View class</blockquote><p>Each element should be given a unique and static view-tag selector. You can then use below in your code:</p><pre>driver.findElement(MobileBy.AndroidViewTag(&quot;&lt;selectorName&gt;&quot;))</pre><figure><img alt="Appium logs espresso" src="https://cdn-images-1.medium.com/max/1024/1*Wf2rX1gHZQSfPKXzA_rBpA.png" /><figcaption>Appium server logs for espresso</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*COE8F785r_6_ZoICX4OlSA.gif" /><figcaption>Appium Espresso</figcaption></figure><p><em>For any issues in starting the Espresso session, one should check Appium server logs as well as Logcat logs.</em></p><h3>Conclusion</h3><p>To conclude, we learnt from this that we can automate android apps using Appium espresso easily. You can find complete set of working desired capabilities and sample apk <a href="https://github.com/sonugupta029/sampleAPK">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b381cbd404" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>