<?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 Ram on Medium]]></title>
        <description><![CDATA[Stories by Ram on Medium]]></description>
        <link>https://medium.com/@ram.machavaram?source=rss-2d71405a3700------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2TOPi-sWSlJ42v67rA_Zlw.jpeg</url>
            <title>Stories by Ram on Medium</title>
            <link>https://medium.com/@ram.machavaram?source=rss-2d71405a3700------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:08:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ram.machavaram/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 Multi-Strategy Self-Healing Selenium Framework: A Practice-Proven POC with Real DOM…]]></title>
            <link>https://medium.com/@ram.machavaram/building-a-multi-strategy-self-healing-selenium-framework-a-practice-proven-poc-with-real-dom-f567f14d86d0?source=rss-2d71405a3700------2</link>
            <guid isPermaLink="false">https://medium.com/p/f567f14d86d0</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ram]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 17:13:59 GMT</pubDate>
            <atom:updated>2025-07-28T17:40:02.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*cW7OR2v4nknBkywO7pJ5Nw.png" /></figure><h3>Building a Multi-Strategy Self-Healing Selenium Framework: A Practice-Proven POC with Real DOM Breakages, Code Samples, and Smart Recovery</h3><p><em>How I used local LLM intelligence, layered heuristics, embeddings, and thorough testing across all locator types to address brittle UI tests.</em></p><h3>The Issue: UI Automation’s Locator Fragility</h3><p>Web apps nowadays are evolving quickly. Dozens of automated UI tests can be broken by a simple class change, attribute renaming, or DOM restructure. These are issues with test maintenance, not product defects.</p><p>I wanted to explore if there’s a smarter way to recover from locator failures using my own adaptive healing approach. So I set out to build a self-healing Selenium framework that doesn’t just fail fast, but heals smartly.</p><h3>The Objective: Learning and Healing Resilient Automation</h3><p>My goal is for the framework to automatically attempt layered strategies to find a dependable fallback in the event that a locator fails, then retain it for later use.</p><blockquote>My guiding principle is to try each approach in turn and only stop when nothing else works.</blockquote><p><em>Implementation note: All </em><em>@FindBy fields are wired via<br></em><em>new HealingFieldDecorator(new HealingElementLocatorFactory(driver)).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4oCq5BOyT4qgeFP4z8qWg.png" /></figure><h3>Strategy 1: Caching for Speed</h3><blockquote>Concept: Every locator failure first checks our cache because repeating work is costly.</blockquote><p><strong>Why this matters:</strong></p><p>Fixing broken locators can be computationally costly, particularly if it calls for attribute similarity matching, DOM diffing, or model inference. It is wasteful to perform that repeatedly for the same locator across test runs or even test steps within a run.</p><p>The main concept here is to <strong>heal once and reuse indefinitely </strong>(or until the user interface changes again).</p><p><strong>How it operates:</strong></p><p>In order to avoid repeating the healing logic in subsequent runs, the plan is to persistently store each selector that has been successfully healed. We use a two-layered storage system to accomplish this:</p><ul><li><strong>Map/HashMap in-memory cache:</strong> incredibly quick lookups that take less than ~5 ms.</li><li><strong>Persistent SQLite DB</strong>: Lightweight, on-disk fallback between sessions is provided by persistent SQLite databases.</li></ul><p><strong>Each time a locator malfunctions, the system:</strong></p><ul><li>First constructs a cacheKey using the current page URL and the original locator string.</li><li>Looks up this key in the in-memory cache.</li><li>If a healed version exists, we instantly return the element using the cached locator.</li><li>If not found, healing is triggered, and once a new working locator is found, it’s <strong>saved to both</strong> the cache and the SQLite DB for future use.</li></ul><h4>Code Sketch</h4><pre><br>String key = driver.getCurrentUrl() + &quot;|&quot; + originalBy;<br>String cached = memoryCache.getOrDefault(key, HealingCache.get(key));<br>if (cached != null) {<br>    healedBy = By.xpath(cached);<br>    DebugLogger.log(now() + &quot;Cache HIT, using: &quot; + healedBy);<br>    return driver.findElement(healedBy);<br>}<br></pre><pre>HealingCache.get(key) // Checks in-memory, else falls back to SQLite</pre><blockquote>Takeaway:</blockquote><blockquote><em>“Most locators only break once. But without caching, you’d pay the full healing cost every time.”</em></blockquote><p>This design ensures that once a locator is healed for a given page, <strong>future tests recover in milliseconds</strong>, completely bypassing expensive logic. It’s healing smart not just healing fast.</p><h3><strong>Strategy 2: Attribute-Based Matching</strong></h3><blockquote>Concept: When simple fixes will do, we score candidates by how closely they resemble the original.</blockquote><p><strong>Why this strategy:</strong></p><p>In the majority of real-world user interfaces, locators fail because an attribute changed such as an id, name, or class change made during a refactor or redesign rather than because the element vanishes. The element itself frequently persists even when the original XPath or CSS locator fails, albeit with somewhat altered properties.</p><p>We can search the visible DOM for candidates that “look like” the original element rather than immediately declaring the test unsuccessful.</p><p><strong>How it operates:</strong></p><p>This method uses fuzzy matching based on attributes. It contrasts the visible elements on the page with the expected attributes of the broken element (tag name, id, name, label text, etc.).</p><p>A straightforward weighted system is used to score each visible DOM element against the original intent:</p><ul><li>Tag name match → high weight</li><li>ID similarity → medium weight</li><li>Name similarity → medium weight</li><li>Label proximity → small but useful signal</li><li>Position/parent structure (optional)</li></ul><p>The candidate with the highest score is used as the healed locator and is thought to be the most likely replacement.</p><p><strong>Code Sketch:</strong></p><pre><br>public String heal(By brokenBy) {<br>    // 1) Extract original attributes<br>    Map&lt;String,String&gt; attrs = extractAttributes(brokenBy);<br>    <br>    // 2) Find all elements<br>    List&lt;WebElement&gt; candidates = driver.findElements(By.xpath(&quot;//*&quot;));<br>    <br>    // 3) Score each element...<br>    WebElement best = null;<br>    double topScore = -1;<br>    for (WebElement c : candidates) {<br>        double score = scoreByTagAndId(c, attrs);<br>        // … additional scoring omitted for brevity<br>        if (score &gt; topScore) {<br>            topScore = score;<br>            best = c;<br>        }<br>    }<br>    <br>    // 4) Return healed XPath if found<br>    return (best != null) <br>        ? LocatorGenerator.generateXPath(driver, best)<br>        : null;<br>}<br></pre><p>This code gives you a pluggable scoring mechanism: you can fine-tune the weights based on what matters most in your app’s DOM structure.</p><p>For instance, let’s say your initial locator was:</p><pre>&lt;input id=&quot;user_email&quot; name=&quot;email&quot; /&gt;</pre><p>Following a UI redesign, the revised DOM features:</p><pre>&lt;input id=&quot;user_email_input&quot; name=&quot;userEmailAddress&quot; /&gt;</pre><p>Although your test fails on the original XPath, the candidate &lt;input&gt; is scored using attribute matching based on:</p><p>Match for tag: Yes</p><p>Fuzzy ID match (user_email_input ~ user_email): Yes</p><p>Fuzzy name match(userEmailAddress ~ email) : Yes</p><p>As a result, it has a high overall score and is chosen as the healed element with confidence.</p><blockquote><strong>Takeaway</strong>:</blockquote><blockquote><em>Attribute-based matching handles the majority of real-world locator failures caused by simple renames or shallow DOM shifts.</em></blockquote><p>It’s <strong>fast, deterministic, and doesn’t require full DOM diffing</strong> or AI inference just smart scoring logic over visible candidates. A great “first responder” healing strategy before escalating to more expensive techniques.</p><h3>Strategy 3: Embedding-Based Semantic Similarity</h3><blockquote>Concept: Match elements by <em>meaning</em>, not just attributes using vector embeddings built from human-readable cues.</blockquote><p>When basic attribute matching can’t save you say, the element’s ID and class are gone, or the DOM has been structurally refactored you need something smarter than plain heuristics. That’s where <strong>embedding-based semantic similarity</strong> comes in.</p><p><strong>What is it?</strong></p><p>Instead of relying on surface-level strings, this strategy builds a <strong>semantic signature</strong> of each element using visible text, tag names, placeholder text, nearby labels, and more. These signatures are then converted into <strong>embedding vectors</strong>, allowing us to calculate <strong>how similar</strong> one element is to another even when they’re structurally different.</p><p><strong>Why do this?</strong></p><ul><li>Refactors often rename or restructure DOMs in ways that break brittle locators.</li><li>Embeddings capture the <strong>purpose</strong> of an element, not just its spelling or position.</li><li>It’s a powerful fallback when everything else fails.</li></ul><p><strong>How it works in the framework</strong></p><p><strong>Step 1: Build a Signature for Each Element</strong></p><p>The signature mimics what a human QA might describe if asked what an element “is” a mix of tag, id, name, placeholder, and visible text.</p><pre>String buildSignature(WebElement e) {<br>    return e.getTagName() + &quot; &quot; +<br>           e.getAttribute(&quot;id&quot;) + &quot; &quot; +<br>           e.getAttribute(&quot;name&quot;) + &quot; &quot; +<br>           (e.getAttribute(&quot;placeholder&quot;) != null ? e.getAttribute(&quot;placeholder&quot;) : &quot;&quot;) + &quot; &quot; +<br>           (e.getText() != null ? e.getText() : &quot;&quot;);<br>}</pre><p><strong>Step 2: Convert Signatures to Embedding Vectors</strong></p><p>Using an internal or lightweight embedding model, we turn strings into numeric vectors (float arrays) that live in a semantic space.</p><pre>float[] targetVec = EmbeddingStore.getEmbedding(buildSignatureFromLocator(brokenBy));<br>float[] candVec   = EmbeddingStore.getEmbedding(buildSignature(candidateElement));</pre><p><strong>Step 4: Accept and Cache the Best Match</strong></p><p>If the top match scores above the threshold (e.g., 0.8), we assume it’s healed, use it, and store it for future runs.</p><pre>if (bestMatch != null &amp;&amp; bestSim &gt; 0.8) {<br>    String healedXPath = LocatorGenerator.generateXPath(driver, bestMatch);<br>    HealingCache.put(key, healedXPath); // Cache for performance<br>    return driver.findElement(By.xpath(healedXPath));<br>}</pre><p><strong>Example in Action</strong></p><p>Let’s say your original locator:</p><pre>@FindBy(xpath = &quot;//input[@id=&#39;user&#39;]&quot;)</pre><p>is now broken. The new element in the DOM is:</p><pre>&lt;input class=&quot;form-input login&quot; placeholder=&quot;User Name&quot; /&gt;</pre><p>Despite no shared ID or name, the embedding signature:</p><pre>input form-input login User Name</pre><p>is semantically similar to the old one. The embedding vectors are close so the system heals it automatically.</p><blockquote>Takeaway:</blockquote><blockquote><em>This is your AI-powered, robust healing for dynamic apps:<br> It doesn’t just match what things are called it matches what they mean.</em></blockquote><p>It’s slower than caching, heavier than attribute-matching, but <strong>dramatically more powerful</strong> when your DOM evolves in unexpected ways.</p><h3>Strategy 4: Local LLM (AI Model) Fallback</h3><blockquote>Concept: As a final fallback, I ask my local LLaMA model to suggest a working selector.</blockquote><p>A local Large Language Model (LLM), like LLaMA running via Ollama, is your framework’s most potent tool when all automated heuristics and embeddings have failed either because the DOM restructure is too great or the locator’s target has changed fundamentally. Designed for resilient healing in extremely dynamic or unpredictable applications, this is the “last line of defense.”</p><h4>Why This Matters</h4><ul><li>Handles the <strong>hardest breakages</strong>: full redesigns, JavaScript-driven UIs, SPAs, or dynamic rendering where no identifiers are predictable.</li><li>Understands intent like a human would based on structure, semantics, and presentation cues.</li><li>Enables healing where even AI embeddings and heuristics fall short.</li></ul><h4><strong>How It Operates:</strong></h4><h4>Step 1: Extract a Targeted HTML Excerpt</h4><p>The framework scopes down to a local neighborhood surrounding the broken locator rather than dumping the entire DOM.</p><pre><br>String htmlSnippet = ContextExtractor.extractSnippet(driver, originalBy, 500); // ~500 chars near failure</pre><h4>Step 2: Build a Smart Prompt for the LLM</h4><p>Feed the model both the <strong>broken locator</strong> and the <strong>scoped DOM snippet</strong>, asking for a healed locator.</p><pre>String prompt = String.format(<br>  &quot;You are an expert in robust Selenium selectors.\n&quot; +<br>  &quot;The original locator: %s\n&quot; +<br>  &quot;HTML snippet:\n%s\n&quot; +<br>  &quot;Suggest ONE valid XPath (or CSS selector) that finds the same element. Return ONLY the locator.&quot;,<br>  originalBy, htmlSnippet<br>);</pre><h4>Step 3: Query the LLM with Timeout</h4><p>We ensure test execution doesn’t hang. Your client talks to a <strong>locally hosted LLM</strong>, like LLaMA via Ollama, with strict execution limits.</p><pre>String llmResp = LlamaApiClient.askSync(prompt, 20, 0.0, 3000);<br>String suggestion = ResponseParser.extract(llmResp);<br>if (suggestion != null) {<br>    By healed = suggestion.startsWith(&quot;//&quot;)<br>        ? By.xpath(suggestion)<br>        : By.cssSelector(suggestion);<br>    HealingCache.put(key, suggestion);<br>    return driver.findElement(healed);<br>}</pre><p>Extract and test the LLM’s output to ensure it’s a valid XPath or CSS selector.</p><pre>String xp = ResponseParser.extract(llmResp);<br>if (xp != null) {<br>    By healed = xp.startsWith(&quot;//&quot;) ? By.xpath(xp) : By.cssSelector(xp);<br>    HealingCache.put(key, xp); // Cache for next time<br>    return driver.findElement(healed);<br>}</pre><h4>Step 5: Cache and Forget</h4><p>Once the LLM heals it, it’s never asked again for the same scenario. All future calls hit your blazing-fast healing cache.</p><p><strong>Example</strong></p><p>Say this locator:</p><pre>@FindBy(xpath = &quot;//button[@type=&#39;submit&#39; and @id=&#39;login&#39;]&quot;)</pre><p>breaks after a redesign. Now the button looks like:</p><pre>&lt;button class=&quot;btn-primary&quot;&gt;Sign In&lt;/button&gt;</pre><p>The LLM sees:</p><ul><li>Original intent: a login or submit action</li><li>HTML snippet: “Sign In” is the new visible clue</li></ul><p>…and replies with:</p><pre>//button[contains(text(),&#39;Sign In&#39;)]</pre><ul><li>It works.</li><li>It’s cached.</li><li>It’s never broken again (until <em>that</em> changes).</li></ul><h4>Why Is This Effective?</h4><ul><li>Reasoning at the human level regarding structure and purpose</li><li>Manages dynamic rendering and drastic HTML rewrites.</li><li>Works even in the event that DOM-tree, semantic vector, or attribute-based strategies don’t work.</li><li>Requires neither network calls nor external services because it operates entirely locally.</li><li>Only occurs on first-time failures and adds very little latency (3s).</li></ul><blockquote>Takeaway</blockquote><blockquote><em>Local LLM Fallback is your AI safety net<br> it doesn’t just recover from failures, it </em>understands<em> them.</em></blockquote><p>It’s what gives your framework true resilience bridging the gap between test automation and human-like adaptability. And best of all it’s private, deterministic, and cache-friendly.</p><h3>Performance Hierarchy: How Fast Is Each Healing Strategy?</h3><p>Here’s a breakdown of how your self-healing framework scales from lightning-fast to intelligent last-resort based on how it resolves a broken locator:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*DTN_rl1_DeTCfuxR3xD7wQ.png" /></figure><blockquote><strong>Every successful heal is cached instantly.</strong><br> So even if you pay the cost once, you’ll never pay it again.<br> <strong>First heal is the last one needed.</strong></blockquote><p>With the help of this layered healing technique, your test suite will continue to be quick and robust, adapting to UI changes without becoming a performance snag.</p><h3>How I Put the Self-Healing Framework to the Test: An Extensive Validation on Practice Websites</h3><blockquote>Using a systematic testing methodology to move from theory to practical validation</blockquote><h4>The Testing Philosophy: Realistic Breakages, Not Artificial Failures</h4><p>I created a thorough testing approach that mimics the real DOM modifications developers make in real applications, as opposed to merely adding “_BROKEN” to functional locators. Verifying the framework’s ability to manage realistic scenarios found in production settings was the aim.</p><h4>Testing Ground: Deep Dive Practice Website</h4><p>Because it provides a variety of UI patterns frequently seen in web applications, I decided to use <a href="https://practice.expandtesting.com/">https://practice.expandtesting.com</a> as my main testing ground:</p><ul><li>Login forms with different kinds of fields</li><li>Validation of forms with intricate inputs</li><li>State-changing dynamic controls</li><li>Tables with content that can be sorted</li><li>Several checkbox/radio patterns</li></ul><h4>Here’s how I systematically tested each area:</h4><h4>Login Page Testing: Core Authentication Flows</h4><p>The login page became my primary testbed for fundamental locator healing scenarios.</p><h4>Realistic Broken Locators Tested:</h4><pre>public class LoginPage {<br>    @FindBy(xpath = &quot;//form[@id=&#39;login&#39;]//textarea[@id=&#39;username&#39;]&quot;)<br>    private WebElement usernameField;<br><br>    @FindBy(id = &quot;pwd&quot;)<br>    private WebElement passwordField;<br><br>    @FindBy(xpath = &quot;//div[@class=&#39;btn-wrapper&#39;]//button[@type=&#39;submit&#39;]&quot;)<br>    private WebElement submitButton;<br><br>    @FindBy(className = &quot;alert-warning&quot;)<br>    private WebElement errorMessage;<br>}</pre><h4>Test Scenarios Executed:</h4><pre>@Test(description = &quot;Valid login with healed tag change&quot;)<br>public void testValidLoginWithTagChangeHealing() {<br>    LoginPage loginPage = new LoginPage(getDriver());<br>    loginPage.navigateToLogin();<br>    loginPage.login(&quot;practice&quot;, &quot;SuperSecretPassword!&quot;);<br>    Assert.assertTrue(getDriver().getCurrentUrl().contains(&quot;secure&quot;));<br>}<br><br>@Test(description = &quot;Invalid login with attribute change healing&quot;)<br>public void testInvalidLoginWithAttributeHealing() {<br>    LoginPage loginPage = new LoginPage(getDriver());<br>    loginPage.navigateToLogin();<br>    loginPage.login(&quot;invalid&quot;, &quot;wrong&quot;);<br>    Assert.assertTrue(loginPage.isErrorMessageDisplayed());<br>}</pre><h4>Form Validation Testing: Complex Input Scenarios</h4><p>Form validation pages test the framework’s ability to handle diverse input types and structural changes.</p><h4>Multi-Type Locator Breakages:</h4><pre>public class FormValidationPage {<br>    @FindBy(xpath = &quot;//textarea[@name=&#39;contactName&#39;]&quot;)<br>    private WebElement contactNameInput;<br><br>    @FindBy(id = &quot;contactPhone&quot;)<br>    private WebElement contactNumberInput;<br><br>    @FindBy(xpath = &quot;//div[@class=&#39;date-picker&#39;]//input[@name=&#39;pickupDate&#39;]&quot;)<br>    private WebElement pickupDateInput;<br><br>    @FindBy(name = &quot;payment&quot;)<br>    private WebElement paymentSelect;<br><br>    @FindBy(xpath = &quot;//footer//button[text()=&#39;Submit&#39;]&quot;)<br>    private WebElement submitButton;<br>}</pre><h4>Test Scenarios Executed:</h4><pre>@Test(description = &quot;Complete form submission with multiple healing strategies&quot;)<br>public void testMultiStrategyFormHealing() {<br>    FormValidationPage formPage = new FormValidationPage(getDriver());<br>    formPage.navigateToFormValidation();<br>    formPage.fillContactName(&quot;John Doe&quot;);<br>    formPage.fillContactNumber(&quot;123-456-7890&quot;);<br>    formPage.fillPickupDate(&quot;01-12-2024&quot;);<br>    formPage.selectPaymentMethod(&quot;Credit Card&quot;);<br>    formPage.clickSubmit();<br><br>    String currentUrl = getDriver().getCurrentUrl();<br>    Assert.assertTrue(currentUrl.contains(&quot;form-validation&quot;) || currentUrl.contains(&quot;success&quot;));<br>}</pre><h4>Dynamic Controls Testing: State-Based Interactions</h4><p>Dynamic controls test the framework’s ability to handle elements that change state or disappear/reappear.</p><h4>Complex XPath Healing Scenarios:</h4><pre>public class DynamicControlsPage {<br>    @FindBy(xpath = &quot;//input[@type=&#39;radio&#39;]&quot;)<br>    private WebElement checkbox;<br><br>    @FindBy(xpath = &quot;//div[@class=&#39;control-wrapper&#39;]//button[text()=&#39;Remove&#39;]&quot;)<br>    private WebElement removeButton;<br><br>    @FindBy(xpath = &quot;//button[translate(text(),&#39;ENABLE&#39;,&#39;enable&#39;)=&#39;enable&#39;]&quot;)<br>    private WebElement enableButton;<br>}</pre><h4>Dynamic Interaction Testing:</h4><pre> @Test(description = &quot;Dynamic element state changes with healing&quot;)<br>public void testDynamicStateHealing() {<br>    DynamicControlsPage dynamicPage = new DynamicControlsPage(getDriver());<br>    dynamicPage.navigateToDynamicControls();<br>    if (dynamicPage.isCheckboxVisible()) {<br>        dynamicPage.clickCheckbox();<br>        dynamicPage.clickRemove();<br>        WebDriverWait wait = new WebDriverWait(getDriver(), Duration.ofSeconds(10));<br>        wait.until(d -&gt; dynamicPage.getStatusMessage().contains(&quot;gone&quot;));<br>    }<br>    dynamicPage.clickAdd();<br>    dynamicPage.clickEnable();<br>}</pre><h4>Edge Cases and Stress Testing</h4><p><strong>Impossible Locators (Graceful Failure Testing):</strong></p><pre>public class EdgeCaseTests extends BaseTest {<br>    @Test(description = &quot;Framework handles impossible locators gracefully&quot;)<br>    public void testImpossibleLocatorGracefulFailure() {<br>        ImpossibleLocatorPage impossiblePage = new ImpossibleLocatorPage(getDriver());<br>        getDriver().get(&quot;https://practice.expandtesting.com/login&quot;);<br>        Assert.assertThrows(() -&gt; impossiblePage.interactWithImpossibleElement());<br>    }<br><br>    private static class ImpossibleLocatorPage {<br>        @FindBy(xpath = &quot;//completely/nonexistent/hierarchy[@impossible=&#39;true&#39;]&quot;)<br>        private WebElement impossibleElement;<br><br>        @FindBy(css = &quot;fake-tag[nonexistent-attr=&#39;impossible&#39;]&quot;)<br>        private WebElement fakeElement;<br><br>        public ImpossibleLocatorPage(WebDriver driver) {<br>            PageFactory.initElements(<br>                new HealingFieldDecorator(new HealingElementLocatorFactory(driver)),<br>                this<br>            );<br>        }<br><br>        public void interactWithImpossibleElement() {<br>            impossibleElement.click();<br>        }<br>    }<br>}</pre><h4>Rapid Cache Performance Testing:</h4><pre>@Test(description = &quot;Cache performance under rapid interactions&quot;)<br>public void testRapidCachePerformance() {<br>    LoginPage loginPage = new LoginPage(getDriver());<br>    loginPage.navigateToLogin();<br>    long startTime = System.currentTimeMillis();<br>    loginPage.enterUsername(&quot;cache_test_1&quot;);<br>    // Subsequent cache-based calls would be faster<br>}</pre><h4>Real DOM Change Scenarios Validated:</h4><ul><li><strong>Tag changes</strong> (input ↔ textarea ↔ select)</li><li><strong>Attribute renames</strong> (id ↔ name ↔ class transitions)</li><li><strong>Hierarchy restructuring</strong> (wrapper additions/removals)</li><li><strong>Text modifications</strong> (button labels, placeholders)</li><li><strong>Type changes</strong> (checkbox ↔ radio ↔ text ↔ password)</li></ul><h3>Database Evidence: Healing in Action</h3><p>The persistent cache (healing-cache.db) provided concrete evidence of successful healing:</p><pre>url: https://practice.expandtesting.com/login<br>original_locator: By.xpath: //textarea[@id=&#39;username&#39;]  <br>healed_xpath: //input[@name=&#39;username&#39;]<br>created_at: 2024-12-15 10:30:15<br>usage_count: 12<br><br>url: https://practice.expandtesting.com/form-validation  <br>original_locator: By.id: contactPhone<br>healed_xpath: //input[@name=&#39;contactNumber&#39;]<br>created_at: 2024-12-15 10:31:22<br>usage_count: 8</pre><h3>Key Insights from Practice Website Testing</h3><p><strong>What Worked Exceptionally Well:</strong></p><ul><li>Attribute-based healing caught the changes</li><li>Embedding similarity recovered complex semantic changes</li><li>LLM fallback handled edge cases missed by heuristics</li><li>Caching eliminated repeated healing costs</li></ul><p><strong>Surprising Discoveries:</strong></p><ul><li>Simple fuzzy matching was more effective than expected</li><li>Context extraction quality heavily influenced LLM success</li><li>False positive prevention required robust validation logic</li></ul><h3>Conclusion</h3><p><strong>Building a Multi-Strategy Self-Healing Selenium Framework</strong> wasn’t just a technical exercise it was a practical deep dive into solving the chronic fragility of UI test automation.</p><p>This framework showed that recovering from the locator failures is feasible through methodical testing on intentionally broken locators and real-world DOM mutations. Real-time healing across a variety of UI changes was made possible by the layered approach, which included local LLM fallback, attribute-based matching, semantic embeddings, and caching.</p><p>However, this is not a plug-and-play solution, rather, it is a proof of concept. Real-world applications are messier, even though results on controlled environments such as practice.expandtesting.com were strong ( sub-200ms average recovery, and instant cache hits). Other difficulties include third-party widgets, async rendering, dynamic SPAs, and deeply nested structures.</p><h4>What t<em>his proof-of-concept demonstrated</em></h4><ul><li>Future research must include the following in order to advance this framework to enterprise-grade status:</li><li>Semantic modeling and deeper context extraction for intricate component trees</li><li>Training models on domain-specific user interfaces</li><li>Strong validation and prevention systems for false positives</li><li>Perhaps incorporating lightweight computer vision or visual heuristics</li></ul><h3>Final Thought</h3><p>This experience demonstrated that, when healing techniques are carefully layered and put to the test against actual breakages, <strong>self-healing is real</strong>, feasible, and quantifiable.</p><p>If you are motivated to create your own healing layer, begin with real-world failures, test each modification, and view each brittle locator as a chance to improve the intelligence of your framework.</p><p><strong>Resilient automation is a mindset rather than a panacea</strong>. And we’re just getting started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f567f14d86d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Automated Testing: Strategies to Succeed]]></title>
            <link>https://medium.com/@ram.machavaram/the-art-of-automated-testing-strategies-to-succeed-aee055f5bb15?source=rss-2d71405a3700------2</link>
            <guid isPermaLink="false">https://medium.com/p/aee055f5bb15</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[automation-testing]]></category>
            <dc:creator><![CDATA[Ram]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 16:48:55 GMT</pubDate>
            <atom:updated>2024-06-28T16:48:55.930Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide will cover information, best practices and few examples to help you create a test automation strategy that works for your team.</p><h3>Why you need a test automation strategy?</h3><p>Automated testing is a major part of today’s software development process, let alone facilitating teams with better efficiency, faster time-to-market, and high-quality products. However, a lack of clear strategy will overshadow its benefits with issues relating to Test Coverage, high maintenance overhead, and disjointed processes. Here, the robust automation strategy comes to address these challenges by providing a structured framework for aligning the testing efforts towards the business goals.</p><h3>Key Elements of a Test Automation Strategy</h3><h4>Choosing the Right Tools</h4><p>Your automation tool selection can make or break your automation initiative. Choose based on how well it integrates with current technologies, rolls into CI/CD pipelines easily and scale out of the box but still can cover a diverse set of applications.</p><blockquote>For example in the case of the Finance project, it should be hybrid automation framework that could interface seamlessly with our mainframe systems and test end-to-end between legacy applications with modern apps.</blockquote><h4>Defining the Scope</h4><p>It is paramount to define the scope for automation, as it determines the size of the ROI and the efficiency of the solution. The first concern is reducing expenses, and the best options are automating tasks that have to be repeated many times and require a lot of effort.</p><blockquote>For example, in an e-commerce application, there could be two key elements to be tested: checkout and user authentication. As initially developed, these modules are relatively uncomplicated, so modifying them might appear to be relatively easy to test manually in-house. To make sure that they indeed work in different scenarios requires significant retesting efforts. There are many parameters — for instance, number of users, network latencies, transaction volumes — which can have different impacts on the effect in these components. Due to this fact, thorough testing is a must, consuming much time and a lot of effort in order to ensure smooth running in all scenarios.</blockquote><h4>Establishing a Test Automation Approach</h4><p>Well-structured framework that enables the process, roles, and responsibilities to be clearly defined within your QA team. The approach ensures the consistency and efficiency of test activities by setting out specific guidelines on how to create, run, and maintain automated tests. It defines roles, like test automation engineers for the development and maintenance of frameworks, and testers for the designing of test cases and execution. Therefore, teams can, thereby, streamline workflow and improve the overall quality of testing. It comprises defined processes such as creating test scripts, version control systems, integration with pipelines in CI/CD, and reporting mechanisms to leverage a consistent collaborative environment that enables meeting testing objectives effectively.</p><blockquote>For example, using Agile methodologies to our benefit, we integrated test automation into the sprint cycles for continuous feedback and fast failure resolution. This increased the speed of testing but augmented the collaboration between the development and QA teams.</blockquote><h4>Setting Clear Objectives</h4><p>Have every automation goal aligned to business objectives so that eventually, success can be based on measurement. Common examples of objectives include: increase test coverage, reduce time spent on manual testing, improve software quality, and decrease production defects.</p><blockquote>In a healthcare project, one of the objectives was to provide 95% test coverage of critical patient management modules so that their system is reliable and results in health care.</blockquote><h4>Conducting Risk Analysis</h4><p>Identify some potential automation risks, such as tool compatibility issues, data security concerns, or environmental dependencies. Robust test protocols are to be implemented with mitigation against risks, including virtualization techniques that would simulate the production environment.</p><blockquote>Imagine you are going to develop a new mobile banking application. Before the deployment, we will do an in-depth risk analysis on automated testing. Our results spelled out faults in the transactions during peak hours and incompatibility with different mobile devices and operating systems. Automated test cases were, therefore, mapped out where heavy user traffic conditions, a variety among users, and differing network conditions were injected into the mobile banking application to mitigate these identified risks. Such proactive strategy not only allowed us to reveal critical bugs by the beginning of the development cycle but ensured that the application was reliable under real-world conditions, too. By applying risk analysis in our automated testing strategy, we minimized deployment risks as much as possible and brought a robust banking solution to our user.</blockquote><h4>Building a Stable Test Environment</h4><p>Stable test environments are important if you are to have meaningful and consistent test results. Mirror production configurations, datasets, and network conditions to reproduce real-world scenarios to a tee.</p><blockquote>In a healthcare project for EMR, Docker-based containerization became indispensable in enhancing the testing capability. Critical components of our EMR system, such as patient data management and integration of diagnostic tools, were containerized to isolate testing environments very close to a production setup that helped run end-to-end tests with external healthcare systems and compliance with regulatory standards. It provided excellent scalability and portability of Docker containers that let us efficiently reproduce complicated configurations of a network and simulate a user’s various activities. Hence, speeding up the process of bug identification and validation of system updates for reliability and security hardening of our EMR platform across different healthcare environments.</blockquote><h4>Developing an Execution Plan</h4><p>Define a structured execution plan that provides scheduling, prioritizing, and monitoring of automated tests, besides continuous integration and continuous deployment practices, to receive fast feedback loops, enabling early detection of defects.</p><blockquote>It was required to develop a meticulous execution plan with respect to transaction processing in the Fintech project. We designed a structured approach that comprises meticulous scheduling, prioritization, and real-time monitoring of automated tests. Putting into practice the principles of continuous integration and continuous deployment, we implemented a robust framework that would permit rapid cycles of feedback for the early identification of defects. Concretely, we automated full Regression tests end-to-end integrated with GitLab CI/CD pipelines. This integration gave the assurance of consistent builds and fast delivery of enhancements and fixes.</blockquote><h3>Best Practices for Test Automation That Is Maintainable and Scalable</h3><h4>Focus on high ROI automation:</h4><p>Identify test cases that would return the greatest value for the investment and focus all your energy on them, for instance, critical path functionalities or frequently executed workflows.</p><h4>Modular Test Designs:</h4><p>Modular test designs are implemented for reusability and maintenance. For example, at one manufacturing project, we utilized Page Object Model to encapsulate UI interactions with a view to making test maintenance and updates easier.</p><h4>Continuous Testing:</h4><p>Build a culture of continuous testing to ensure constant validation of software quality throughout the lifecycles. Implement automated regression suites.</p><h4>Tool Selection:</h4><p>Choose tools that scale correctly for your project and align with the skills of your team. This includes everything from scripting languages and test framework support to community backing for long-term viability.</p><h3>Implementing Your Test Automation Strategy</h3><h4>Planning and Preparation</h4><p>Firstly, understand the project requirements, stakeholder expectations, and the existing infrastructure in detail. Interact with cross-functional teams to derive inputs to define automation goals from business objectives.</p><blockquote>For example, workshops were held with stakeholders to identify key workflows and establish feasibility for automation.</blockquote><h4>Framework Development</h4><p>Create a robust automation infrastructure that is customized for your application’s structure as well as examination requirements. It could be any common industry framework such as Selenium WebDriver for online apps or Appium designed for mobile app testing. Amends will be made on how structures facilitate data-driven assessments, parallel run and third-party API integration.</p><blockquote>In an application concerning health, we can design a hybrid framework combining BDD concepts with Selenium for building effective test scenarios and validation against complex regulatory requirements.</blockquote><h4>Creation of Test Scripts</h4><p>Write small, easy-to-maintain test scripts according to the best practices of coding and the rules of the project. Version control systems will make collaborative script versioning and version management possible.</p><h3>Conclusion</h3><p>A good test automation strategy supports the core pillars of sustainable software quality, time-to-market, and stakeholder confidence. Guided by principles and best practices, you will be better placed to iron out bumps in your automation journey, minimize project risks, and realize measurable improvements in the delivery of software. Embrace automation as the driver of innovation and quality in genuinely enabling teams to focus on strategic initiatives and business growth.</p><p>Apply these strategies diligently and with flexibility to be able to succeed in evolving technological landscapes and market dynamics. Remember, having the ability to automate correctly is not the use of tools and scripts rather ensuring teamwork, enhancement and no-rest search for quality in software testing.</p><blockquote>Fundamental methods are what have been discussed within ‘The Art of Automated Testing,’ however, there may yet be more topics that need further probing.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aee055f5bb15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Your Automation Framework from Java 8 to Java 17]]></title>
            <link>https://medium.com/@ram.machavaram/migrating-your-automation-framework-from-java-8-to-java-17-37100fdd6f52?source=rss-2d71405a3700------2</link>
            <guid isPermaLink="false">https://medium.com/p/37100fdd6f52</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <dc:creator><![CDATA[Ram]]></dc:creator>
            <pubDate>Sun, 16 Jul 2023 16:28:15 GMT</pubDate>
            <atom:updated>2023-07-16T16:28:15.423Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Selenium FW Migrating Java 8 to Java 17</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9gBFaK031Wubt1yxAD0Zw.png" /><figcaption><strong>Selenium FW Migrating Java 8 to Java 17</strong></figcaption></figure><h4>Introduction:</h4><p>In the ever-evolving world of software development, it’s crucial to adapt and embrace new technologies to stay ahead. That’s why we have an important announcement regarding the future of Selenium: Starting from September 30, 2023, Selenium will no longer support Java 8. This change applies to both the Java bindings and the Selenium Grid.</p><p><a href="https://www.selenium.dev/blog/2023/java-8-support/">Java 8 support in Selenium</a></p><p>Firstly, Java 8 reached the end of active support over a year ago. By moving away from Java 8, we can ensure that Selenium users benefit from the latest security updates and bug fixes, enhancing the overall stability and reliability of their automation frameworks.</p><blockquote>Selenium will be Java 11. It’s important to note that active support for Java 11 will also come to an end on September 30, 2023. They will revisit the topic in the future to announce their plan for supporting Java 17 as the minimum required version.</blockquote><p>To facilitate a smooth transition and automate the migration process, we recommend leveraging the power of OpenRewrite. OpenRewrite is a powerful tool that simplifies the migration from Java 8 to Java 17 by automatically addressing common issues and applying necessary code transformations. With OpenRewrite, you can save valuable time and effort in the migration process, ensuring a seamless upgrade to Java 17.</p><p>In this blog post, we will guide you through the process of migrating your automation framework from Java 8 to Java 17, with a focus on leveraging OpenRewrite. We’ll provide step-by-step instructions, best practices, and practical examples to help you navigate the migration process with ease.</p><p>By upgrading to Java 17, I was able to take advantage of improved performance, enhanced security, and access to new language features. In this blog post, I’ll discuss the steps I followed and introduce OpenRewrite, a powerful tool that automated the migration process.</p><h4>Improved Performance:</h4><p>Upgrading your automation framework to Java 17 brings a host of performance optimizations that can significantly enhance the efficiency and speed of your automation runs. Java 17 introduces advancements in garbage collection, just-in-time (JIT) compilation, and overall runtime performance, resulting in faster execution times for your automation tests.</p><p>By leveraging these performance improvements, you can streamline your test execution, reduce test run times, and increase overall productivity. Faster test runs allow for quicker feedback on code changes, expedite release cycles, and enable more efficient use of testing resources.</p><h4>Enhanced Security:</h4><p>Security is a critical aspect of any automation framework, especially when dealing with sensitive data and interacting with various systems and resources. By migrating to Java 17, you ensure that your automation framework benefits from the latest security updates and features, helping to safeguard against potential vulnerabilities.</p><p>Java 17 incorporates enhanced security measures, including updated cryptographic algorithms and strengthened security protocols. These advancements bolster the security of your automation framework, mitigating risks and providing a more secure testing environment. Staying current with the latest security patches and features helps protect against potential cyber threats and ensures compliance with security standards.</p><h4>New Language Features:</h4><p>Java 17 introduces exciting language features that enhance expressiveness, code simplicity, and maintainability. By upgrading your automation framework to Java 17, you gain access to these features and can leverage them to improve your codebase.</p><p>For instance, the introduction of<strong> records in Java 17</strong> simplifies the creation of classes primarily used for data storage. Records generate essential methods, such as constructors, getters, and equals() and hashCode() methods, automatically reducing boilerplate code. This streamlines your codebase, making it more concise, readable, and easier to maintain.</p><p><strong><em>Pattern matching</em></strong>, another powerful feature in Java 17, allows for more efficient and expressive conditional logic. It enables you to match patterns within data structures, simplifying the extraction and processing of specific elements. By leveraging pattern matching, you can reduce code complexity, improve readability, and enhance the maintainability of your automation code.</p><p><strong><em>Sealed classes</em></strong>, a feature introduced in Java 17, provide better control over class hierarchies by restricting the set of allowed subclasses. This promotes encapsulation and ensures that the inheritance structure within your automation framework is well-defined and maintainable. By utilizing sealed classes, you can enforce design constraints and enhance the clarity and robustness of your codebase.</p><p>In summary, migrating your automation framework from Java 8 to Java 17 is crucial for unlocking improved performance, enhanced security, and access to powerful language features. Upgrading ensures that your automation framework operates at peak efficiency, protects against potential vulnerabilities, and enables the adoption of modern coding practices. By embracing the advancements offered by Java 17, you can optimize your automation runs, strengthen the security of your framework, and develop more maintainable and expressive automation code.</p><h3>Using OpenRewrite for Automated Migration:</h3><p>To facilitate the migration process, I utilized OpenRewrite, a powerful tool that automates common migration tasks. Here’s a more elaborate breakdown of how I used OpenRewrite to migrate my automation framework</p><h4>Install OpenRewrite:</h4><ul><li>I incorporated the OpenRewrite plugin into my project by adding the rewrite-maven-plugin as a build plugin in my pom.xml file. This plugin seamlessly integrates with Maven, simplifying the execution of automated code transformations.</li></ul><pre>&lt;build&gt;<br>  &lt;plugins&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.openrewrite.maven&lt;/groupId&gt;<br>      &lt;artifactId&gt;rewrite-maven-plugin&lt;/artifactId&gt;<br>      &lt;version&gt;5.2.6&lt;/version&gt;<br>      &lt;configuration&gt;<br>        &lt;activeRecipes&gt;<br>          &lt;recipe&gt;org.openrewrite.java.migrate.UpgradeToJava17&lt;/recipe&gt;<br>        &lt;/activeRecipes&gt;<br>      &lt;/configuration&gt;<br>      &lt;dependencies&gt;<br>        &lt;dependency&gt;<br>          &lt;groupId&gt;org.openrewrite.recipe&lt;/groupId&gt;<br>          &lt;artifactId&gt;rewrite-migrate-java&lt;/artifactId&gt;<br>          &lt;version&gt;2.0.5&lt;/version&gt;<br>        &lt;/dependency&gt;<br>      &lt;/dependencies&gt;<br>    &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br>&lt;/build&gt;</pre><blockquote><em>Note: The OpenRewrite tool offers a recipe for migrating from Java 8 to Java 11 (&lt;recipe&gt;org.openrewrite.java.migrate.Java8toJava11&lt;/recipe&gt;). However, the choice of which Java version to migrate to is entirely up to us. We can select the version that best fits our project’s needs and objectives, taking into account the benefits and implications of each version.</em></blockquote><p>In this code snippet, I added the rewrite-maven-plugin as a build plugin to my project&#39;s Maven configuration. This plugin seamlessly integrates with Maven, making it effortless to perform automated code transformations during the migration process. The activeRecipes configuration specifies the recipe to use, which, in this case, is UpgradeToJava17 provided by the rewrite-migrate-java dependency.</p><h4><strong>Execute the Migration:</strong></h4><p>After configuring OpenRewrite, I ran the command <strong>mvn rewrite:run</strong> in the root directory of my project. This command triggered OpenRewrite to apply the necessary transformations and migrate the codebase from Java 8 to Java 17.</p><ul><li><strong>During the migration</strong>, OpenRewrite extensively analyzed my codebase, identifying areas that required modification to align with Java 17. It implemented a series of automated transformations, such as updating APIs, refactoring deprecated features, and adapting code to conform to Java 17 language changes.</li><li><strong>Review and Manual Fixes</strong>: Following the execution of the migration, it was crucial to meticulously review the changes made by OpenRewrite. I employed tools like git diff to examine the modifications introduced in my codebase. Although OpenRewrite expertly handled the automatic migration, there were instances where manual fixes were necessary.</li><li><strong>During the review process</strong>, it was important to scrutinize any areas where the automated transformations might not have fully captured the desired outcome. These instances could involve specific code patterns that required specialized handling or adaptations. By meticulously reviewing and addressing these cases, I ensured the integrity and correctness of my migrated automation framework.</li><li><strong>During the manual fixes</strong>, it was necessary to make targeted adjustments to specific code sections to align with Java 17 syntax, update API usages, or refactor any remaining deprecated features. It was crucial to adhere to best practices and leverage the knowledge of Java 17’s new language features to optimize and enhance the codebase further.</li></ul><blockquote>Remember to conduct thorough testing of your automation framework after the migration to ensure that it functions correctly and maintains the expected behavior.</blockquote><p>By utilizing OpenRewrite, the migration process was streamlined through the automation of many common migration tasks. However, it was important to review the specific changes introduced by OpenRewrite and apply any necessary manual fixes to ensure a successful migration to Java 17.</p><p>By leveraging OpenRewrite, you can save time and effort while migrating your automation framework, enabling you to quickly take advantage of the benefits offered by Java 17. The automated transformations provided by OpenRewrite help streamline the migration process and ensure that your codebase adheres to Java 17’s syntax and best practices.</p><h4><strong>Conclusion:</strong></h4><p>The migration of my automation framework from Java 8 to Java 17 using OpenRewrite proved to be a seamless and efficient process. By integrating the rewrite-maven-plugin into my project and executing the migration with mvn rewrite:run, I automated the code transformations required to align with Java 17. OpenRewrite adeptly handled various migration tasks, such as updating APIs, refactoring deprecated features, and adapting code to conform to Java 17 language changes.</p><p>After the migration, a thorough review of the changes made by OpenRewrite was crucial. This review process involved examining the modifications introduced in the codebase using tools like git diff. Although OpenRewrite effectively automated the code migration, there were instances where manual fixes were required.</p><p>Through careful review and application of manual fixes, the integrity and correctness of the migrated automation framework were ensured. Thorough testing of the framework further verified its functionality and adherence to expected behavior.</p><p>By leveraging OpenRewrite, the migration process was significantly simplified, saving valuable time and effort. This enabled the swift adoption of Java 17’s improved performance, enhanced security, and new language features in the automation framework. I encourage you to explore OpenRewrite and harness its power to effortlessly migrate your projects to Java 17.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37100fdd6f52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Selenium Grid Management with Zalenium]]></title>
            <link>https://medium.com/@ram.machavaram/simplify-selenium-grid-management-with-zalenium-730c6363c038?source=rss-2d71405a3700------2</link>
            <guid isPermaLink="false">https://medium.com/p/730c6363c038</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[cloud-testing]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[selenium-grid]]></category>
            <category><![CDATA[automation-testing]]></category>
            <dc:creator><![CDATA[Ram]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 07:37:57 GMT</pubDate>
            <atom:updated>2023-07-09T07:38:33.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>#Zalenium</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2V2kYlMN61auv1OmjRahw.png" /></figure><h4>Introduction</h4><p>Running automated tests in multiple browsers can be a complex and time-consuming task. Organizations often need to ensure that their web applications and software are compatible and function correctly across different browsers, such as Firefox and Chrome. To achieve this, they rely on automated testing frameworks like Selenium, which allows them to write and execute test scripts to simulate user interactions and verify the expected behavior.</p><p>By using Zalenium, you can effortlessly scale your test execution based on demand. When test load increases, Zalenium dynamically creates additional browser containers to handle the workload, ensuring optimal resource utilization and reducing test execution time. Once the demand decreases, the excess containers are automatically scaled down and destroyed.</p><p>In summary, Zalenium simplifies the process of running automated tests in multiple browsers by providing a disposable and flexible Selenium Grid infrastructure. It leverages Docker and Kubernetes for seamless integration and allows you to scale your test execution effortlessly. With Zalenium, you can save time and effort in setting up and managing your testing environment, ultimately enhancing your test automation efforts and improving the quality of your software.</p><h4><strong>What is Zalenium?</strong></h4><ul><li>Zalenium provides a disposable and flexible Selenium Grid infrastructure.</li><li>It integrates with Docker and Kubernetes.</li><li>It enables quick setup and tear-down of browser containers for test execution.</li><li>Zalenium allows running tests in Firefox and Chrome browsers.</li><li>It supports dynamic scaling of the grid based on demand.</li></ul><h4><strong>Key Features</strong></h4><ul><li><strong>Dynamic Scaling</strong>: Zalenium scales up and down dynamically, optimizing resource utilization and reducing test execution time.</li><li><strong>Browser Support</strong>: Zalenium supports running tests in Firefox and Chrome. It integrates with cloud testing providers like Sauce Labs, BrowserStack, and TestingBot for additional browser support.</li><li><strong>Custom Capabilities</strong>: Zalenium offers capabilities to customize the testing environment, such as specifying screen resolutions, time zones, and disabling test recording.</li><li><strong>Dashboard and Monitoring</strong>: Zalenium provides a user-friendly dashboard for real-time insights into test execution. It allows monitoring of test status, access to recorded videos, and review of aggregated logs.</li><li><strong>Docker and Kubernetes Compatibility</strong>: Zalenium seamlessly integrates with both Docker and Kubernetes, giving flexibility in deployment choices.</li></ul><p>By organizing the information into these modules or topics, it becomes easier to understand the different aspects of Zalenium and its features.</p><h4>Getting Started:</h4><p>To start using Zalenium, follow these steps:</p><h4>Prerequisites</h4><ul><li>Docker version &gt;= 1.11.1 (probably works with earlier versions, not tested yet).</li><li>Make sure that docker info works without errors.</li><li># Pull docker-selenium</li></ul><pre>docker pull elgalu/selenium</pre><p>1. Pull Docker Images:</p><p>Before using Zalenium, you need to pull the necessary Docker images. Docker images are pre-packaged environments that contain all the dependencies and configurations required for running specific software.</p><p>To pull the Zalenium Docker image, open your terminal or command prompt and run the following command:</p><pre>docker pull dosel/zalenium:latest</pre><p>This command will download the latest version of the Zalenium Docker image from the Docker Hub repository.</p><h4>2. Run Zalenium:</h4><p>Once you have the Zalenium Docker image, you can start the Zalenium container. The container runs an instance of Zalenium with the specified configurations.</p><p>Make sure docker should have complete privilege on the folder given at below command.(Docker&gt;&gt; Settings&gt;&gt; Shared Drives)</p><p>To start the Zalenium container, run the following command:</p><pre>docker run --rm -ti --name zalenium -p 4444:4444 -v /var/run/docker.sock:/var/run/docker.sock -v /c/Users/admin/tmp/videos:/c/Users/admin/tmp/videos --privileged dosel/zalenium startLet’s break down the parameters used in the above command:</pre><ul><li>--rm: Automatically remove the container when it stops running.</li><li>-ti: Allocate a pseudo-TTY and keep STDIN open to interact with the container.</li><li>--name zalenium: Assign a name (&quot;zalenium&quot;) to the container for easy identification and management.</li><li>-p 4444:4444: Map port 4444 of the container to port 4444 on the host machine. This allows communication with the Selenium Grid.</li><li>-v /var/run/docker.sock:/var/run/docker.sock: Mount the Docker socket inside the container. This enables communication between the container and the Docker daemon.</li><li>-v /tmp/videos:/home/seluser/videos: Mount the host machine&#39;s &quot;/tmp/videos&quot; directory to the &quot;/home/seluser/videos&quot; directory inside the container. This is where Zalenium saves the video recordings of test sessions.</li><li>--privileged: Give extended privileges to the container. This is required to manage the browser containers effectively.</li></ul><p>When you run the above command, Docker will start the Zalenium container and it will be accessible at http://localhost:4444/wd/hub. This is the URL you will use to connect to the Zalenium Grid in your Java code.</p><h4>3. Add Selenium WebDriver Dependency:</h4><p>To use Selenium WebDriver in your Java project, you need to add the Selenium WebDriver dependency to your project’s build configuration file. Here’s an example using Maven’s pom.xml file:</p><pre>&lt;dependencies&gt;<br>  &lt;dependency&gt;<br>    &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;<br>    &lt;artifactId&gt;selenium-java&lt;/artifactId&gt;<br>    &lt;version&gt;[Version]&lt;/version&gt;<br>  &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>Make sure to adjust the version according to your project’s requirements. You can find the latest version on the Selenium Maven Repository.</p><h4>4. Write a Test Case:</h4><p>Now, let’s write a test case in Java using Selenium WebDriver to interact with the Zalenium Grid and perform automated browser testing. Here’s an example:</p><pre>import org.openqa.selenium.WebDriver;<br>import org.openqa.selenium.WebElement;<br>import org.openqa.selenium.By;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br><br>import java.net.MalformedURLException;<br>import java.net.URL;<br><br>public class ZaleniumExampleTest {<br><br>    public static void main(String[] args){<br>        // Set Zalenium Grid URL<br>     String gridUrl = &quot;http://localhost:4444/wd/hub&quot;;<br><br>     // Define desired capabilities for the browser<br>    DesiredCapabilities capabilities = new DesiredCapabilities();<br>    capabilities.setCapability(CapabilityType.BROWSER_NAME, BrowserType.CHROME);<br>    capabilities.setCapability(CapabilityType.PLATFORM_NAME, Platform.LINUX);<br><br><br>    // Create a WebDriver instance pointing to the Zalenium Grid<br>    RemoteWebDriver driver =new RemoteWebDriver(new URL(gridUrl), capabilities);<br>        // Open a webpage<br>        driver.get(&quot;https://&lt;sampleURL&gt;.com&quot;);<br><br>        // Perform actions on the webpage<br>    System.out.println(&quot;Page Title: &quot; + driver.getTitle());<br>        // Close the browser<br>        driver.quit();<br>    }<br>}</pre><p>In the above code, we start by setting the URL of the Zalenium Grid (gridUrl) to http://localhost:4444/wd/hub, which is the default URL for the Zalenium Grid.</p><p>Next, we define the desired capabilities for the browser using the DesiredCapabilities class. In this example, we set the browser name as &quot;chrome&quot;. You can change the browser name to any supported browser like &quot;firefox&quot; or &quot;safari&quot; based on your requirements.</p><p>Then, we create a new instance of the RemoteWebDriver class, which connects to the Zalenium Grid using the specified URL and desired capabilities.</p><p>After establishing the connection, we can interact with the browser. In this example, we open a webpage (URL), find an element on the page (in this case, the &lt;h1&gt; tag), and print its text to the console.</p><p>Finally, we call driver.quit() to close the browser and release any associated resources.</p><h4>5. Run the Test:</h4><p>To run the test case, make sure that the Zalenium container is running. You can verify this by running docker ps in your terminal or command prompt. You should see the zalenium container listed.</p><p>Once the Zalenium container is up and running, you can execute the Java test case. You can use your preferred Java testing framework (e.g., JUnit, TestNG) to execute the test case or simply run it as a standalone Java application.</p><p>When the test is executed, Zalenium will allocate a browser container, run the test in that container, capture the video recording of the test session, and display the results on the Zalenium dashboard.</p><h4>6. Monitor and Analyze:</h4><p>After running the test, you can monitor and analyze the results using the Zalenium dashboard. The dashboard provides a user-friendly interface for viewing the test execution status, accessing recorded videos, and examining logs.</p><p>To access the Zalenium dashboard, open a web browser and navigate to <a href="https://opensource.zalando.com/zalenium/img/live_preview.gif"><strong>http://localhost:4444/dashboard</strong></a>. From the dashboard, you can view the test results, watch recorded videos, and examine logs to gain insights into your test runs.</p><p>Make sure to refer to the official Selenium documentation (<a href="https://www.selenium.dev/documentation/en/">https://www.selenium.dev/documentation/en/</a>) and Zalenium documentation (<a href="https://opensource.zalando.com/zalenium/">https://opensource.zalando.com/zalenium/</a>) for detailed information on advanced configurations, customization options, and troubleshooting tips.</p><p>Remember to adapt the code examples and configurations according to your specific requirements and project setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=730c6363c038" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Parallel Test Execution with Selenium Grid with Docker]]></title>
            <link>https://medium.com/@ram.machavaram/implementing-parallel-test-execution-with-selenium-grid-with-docker-6c7839b58d7c?source=rss-2d71405a3700------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c7839b58d7c</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <category><![CDATA[selenium-grid]]></category>
            <category><![CDATA[automation-testing]]></category>
            <dc:creator><![CDATA[Ram]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 15:45:27 GMT</pubDate>
            <atom:updated>2023-07-02T15:45:27.198Z</atom:updated>
            <content:encoded><![CDATA[<p>Selenium Grid with Docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*y4zKBoHKLkV8p8mAHlMjnQ.png" /><figcaption>Parallel Test Execution with Selenium Grid with Docker</figcaption></figure><h4><strong>Introduction:</strong></h4><p>In the realm of software testing, the implementation of parallel test execution has gained paramount importance due to its ability to provide quicker feedback and optimize testing resources. A potent solution for achieving parallel test execution is the combination of Selenium Grid with Docker containers. This powerful amalgamation allows testers to efficiently distribute and execute tests across multiple machines or nodes simultaneously, resulting in substantial time savings and improved test coverage.</p><p>Selenium Grid serves as a pivotal tool that facilitates test execution on diverse machines and browsers in parallel. It acts as a central hub, managing and orchestrating the execution of tests across multiple nodes. By harnessing the capabilities of Selenium Grid, testers can seamlessly perform cross-browser testing and parallel test execution.</p><p>Complementing Selenium Grid, Docker is a versatile platform that facilitates the creation and management of lightweight and isolated containers. These containers offer a self-contained environment equipped with all the necessary dependencies required for executing tests, simplifying the setup and maintenance of test environments. The portable nature of Docker containers enables hassle-free deployment on any machine equipped with Docker.</p><p>By combining Selenium Grid with Docker, testers can scale their test execution capabilities by creating multiple containers and distributing tests across them. This setup enables the parallel execution of tests on diverse browsers, operating systems, and machines, thereby enhancing test coverage and significantly reducing the overall test execution time.</p><p>To implement parallel test execution with Selenium Grid and Docker, it is imperative to establish a Selenium Grid hub and multiple Selenium Grid nodes, each operating within Docker containers. The hub serves as a central control point, receiving test requests and efficiently allocating them to available nodes for execution. The nodes, operating within Docker containers, provide the requisite browsers and operating systems necessary for test execution.</p><p>Leveraging Docker containers facilitates the swift provisioning and deprovisioning of test environments, eliminating the need for manual configuration and setup. Additionally, Docker containers ensure the isolation of tests, preventing conflicts that may arise when multiple tests are executed concurrently on different nodes.</p><p>The implementation of parallel test execution with Selenium Grid and Docker empowers testers to achieve faster feedback cycles, improved test coverage, and enhanced efficiency in their testing processes. It enables the concurrent execution of tests across a range of browsers and environments, thereby diminishing the time required for comprehensive testing.</p><p>In conclusion, the fusion of Selenium Grid with Docker provides a robust solution for parallel test execution. It allows testers to harness the potential of distributed testing and containerization, resulting in accelerated testing processes and superior software quality. By embracing this setup, organizations can elevate the quality of their software, expedite application delivery, and ensure an impeccable user experience.</p><blockquote><strong>The process involves two main steps:</strong></blockquote><blockquote><strong><em>setting up Selenium Grid using Docker and configuring your test project to execute tests in parallel.</em></strong></blockquote><h4>Step 1: Setting up Selenium Grid with Docker:</h4><ol><li>Install Docker: Begin by <a href="https://docs.docker.com/engine/install/">installing Docker</a> on your machine. Docker provides a platform to run containers that encapsulate your test environment.</li><li>Create a Docker Compose file: To define your Selenium Grid setup, create a Docker Compose file (e.g., docker-compose.yml). This file specifies the configuration for the Selenium Grid hub and nodes. The hub acts as a central control point, while the nodes represent the machines and browsers where tests will be executed. Here&#39;s an example configuration:</li></ol><pre>version: &quot;3&quot;<br>services:<br>  hub:<br>    image: selenium/hub:latest<br>    ports:<br>      - &quot;4444:4444&quot;<br>    environment:<br>      - GRID_BROWSER_TIMEOUT=300<br>      - GRID_TIMEOUT=300<br>  chrome:<br>    image: selenium/node-chrome:latest<br>    depends_on:<br>      - hub<br>    environment:<br>      - HUB_HOST=hub<br>  firefox:<br>    image: selenium/node-firefox:latest<br>    depends_on:<br>      - hub<br>    environment:<br>      - HUB_HOST=hub</pre><p>Let’s break down this YAML file:</p><ul><li><strong>version: &quot;3&quot;</strong>: This line specifies the version of the Docker Compose file syntax. The version &quot;3&quot; is used in this example.</li><li><strong>services</strong>: This section defines the services (containers) that make up the Selenium Grid infrastructure.</li><li><strong>hub</strong>: This section defines the Selenium Grid hub service.</li><li><strong>image: selenium/hub:latest</strong>: Specifies the Docker image to use for the hub service. In this case, the selenium/hub image is used, and the latest tag represents the latest version available.</li><li><strong>ports: - &quot;4444:4444&quot;</strong>: Maps the host machine&#39;s port 4444 to the container&#39;s port 4444. This allows external connections to the Selenium Grid hub.</li><li><strong>environment: - GRID_BROWSER_TIMEOUT=300 - GRID_TIMEOUT=300</strong>: Sets environment variables for the hub container. In this example, GRID_BROWSER_TIMEOUT and GRID_TIMEOUT are set to 300 seconds, increasing the browser and general timeout values.</li><li><strong>chrome</strong>: This section defines the Selenium Grid node service for Chrome.</li><li><strong>image</strong>: selenium/node-chrome:latest: Specifies the Docker image to use for the Chrome node service. Here, the selenium/node-chrome image with the latest tag is used.</li><li><strong>depends_on: - hub</strong>: Indicates that the Chrome node depends on the hub service. Docker Compose ensures that the hub service starts before the Chrome node.</li><li><strong>environment</strong>: - HUB_HOST=hub: Sets the HUB_HOST environment variable for the Chrome node to point to the hub service. This allows the node to register with the hub.</li><li><strong>firefox</strong>: This section defines the Selenium Grid node service for Firefox.</li><li><strong>image: selenium/node-firefox:latest</strong>: Specifies the Docker image to use for the Firefox node service. Here, the selenium/node-firefox image with the latest tag is used.</li><li><strong>depends_on: - hub</strong>: Indicates that the Firefox node depends on the hub service. Docker Compose ensures that the hub service starts before the Firefox node.</li><li><strong>environment: - HUB_HOST=hub</strong>: Sets the HUB_HOST environment variable for the Firefox node to point to the hub service. This allows the node to register with the hub.</li></ul><p>By defining the hub and node services in the Docker Compose file, you create a Selenium Grid infrastructure with a hub running on port 4444 and Chrome and Firefox nodes registered with the hub. This setup allows you to distribute test execution across multiple browsers and platforms using Selenium Grid and Docker. Ensure that you’re using the latest Selenium images by using the latest tag.</p><p>Start Selenium Grid: Run the Docker Compose command (docker-compose up) in the same directory as your Docker Compose file. This command will start the Selenium Grid hub and nodes based on the defined configuration. You should see output indicating that the containers are running.</p><h4>Step 2: Configuring your test project:</h4><ol><li>Add dependencies: Make sure your test project has the necessary dependencies. You’ll need the Selenium WebDriver library. You can use build tools like Maven or Gradle to manage dependencies.</li><li>Instantiate RemoteWebDriver: Instead of creating a local WebDriver instance, you need to create a RemoteWebDriver instance that connects to the Selenium Grid hub. Here&#39;s an example in Java:</li></ol><pre>import org.openqa.selenium.WebDriver;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br>import java.net.URL;<br><br>public class TestClass {<br>    public static void main(String[] args) {<br>        try {<br>            DesiredCapabilities capabilities = DesiredCapabilities.chrome();<br>            WebDriver driver = new RemoteWebDriver(new URL(&quot;http://localhost:4444/wd/hub&quot;), capabilities);<br>            // Perform your test actions with the WebDriver instance<br>            driver.quit();<br>        } catch (Exception e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>In this example, we create a RemoteWebDriver instance by providing the URL of the Selenium Grid hub (http://localhost:4444/wd/hub). We also specify the desired capabilities for the browser (e.g., Chrome). You can create multiple instances of RemoteWebDriver for different browsers and run tests in parallel.</p><h4>Running tests in parallel:</h4><p>To run tests in parallel, you have a few options depending on your testing framework:</p><ul><li><strong>TestNG or JUnit</strong>: If you’re using a testing framework like TestNG or JUnit, you can configure parallel execution in the test configuration file (e.g., testng.xml for TestNG). Specify the desired parallelization mode (e.g., parallel=&quot;tests&quot;) and ensure that each test class uses a separate instance of RemoteWebDriver.</li></ul><p><strong>Maven project with TestNG as the testing framework</strong></p><ol><li><strong>Add Dependencies</strong>: In your Maven pom.xml file, add the following dependencies for TestNG and Selenium:</li></ol><pre>&lt;dependencies&gt;<br>    &lt;!-- TestNG --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.testng&lt;/groupId&gt;<br>        &lt;artifactId&gt;testng&lt;/artifactId&gt;<br>        &lt;version&gt;7.4.0&lt;/version&gt;<br>        &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Selenium --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;<br>        &lt;artifactId&gt;selenium-java&lt;/artifactId&gt;<br>        &lt;version&gt;4.1.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p><strong>2. Configure TestNG XML File</strong>: Create a TestNG XML file (e.g., testng.xml) in the project&#39;s root directory. This XML file will define test groups and specify the desired browsers for each group.</p><pre>&lt;!DOCTYPE suite SYSTEM &quot;https://testng.org/testng-1.0.dtd&quot; &gt;<br>&lt;suite name=&quot;MyTestSuite&quot;&gt;<br>    &lt;test name=&quot;ChromeTests&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;chrome&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;com.example.TestClass1&quot; /&gt;<br>            &lt;class name=&quot;com.example.TestClass2&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>    &lt;test name=&quot;FirefoxTests&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;firefox&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;com.example.TestClass3&quot; /&gt;<br>            &lt;class name=&quot;com.example.TestClass4&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>&lt;/suite&gt;</pre><p>In this example, two test groups (ChromeTests and FirefoxTests) are defined. Each group specifies the desired browser using the parameter tag, and the respective test classes are included within the classes tag.</p><p><strong>3 . Create Test Classes:</strong></p><p>Create test classes that correspond to the tests defined in the TestNG XML file. Each test class will contain test methods tagged with the desired browser using TestNG’s @Parameters annotation.</p><p>Example test classes:</p><pre>package com.example;<br><br>import org.openqa.selenium.WebDriver;<br>import org.openqa.selenium.chrome.ChromeDriver;<br>import org.openqa.selenium.firefox.FirefoxDriver;<br>import org.testng.annotations.AfterClass;<br>import org.testng.annotations.BeforeClass;<br>import org.testng.annotations.Parameters;<br>import org.testng.annotations.Test;<br><br>public class TestClass1 {<br>    private WebDriver driver;<br><br>    @BeforeClass<br>    @Parameters(&quot;browser&quot;)<br>    public void setup(String browser) {<br>        // Initialize the WebDriver based on the browser parameter<br>        if (browser.equalsIgnoreCase(&quot;chrome&quot;)) {<br>          // Selenium3// System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;path/to/chromedriver&quot;);<br>            driver = new ChromeDriver();<br>        } else if (browser.equalsIgnoreCase(&quot;firefox&quot;)) {<br>           //Selenium3// System.setProperty(&quot;webdriver.gecko.driver&quot;, &quot;path/to/geckodriver&quot;);<br>            driver = new FirefoxDriver();<br>        }<br>    }<br><br>    @Test<br>    public void testMethod1() {<br>        // Test logic using the WebDriver<br>        // ...<br>    }<br><br>    @Test<br>    public void testMethod2() {<br>        // Test logic using the WebDriver<br>        // ...<br>    }<br><br>    @AfterClass<br>    public void teardown() {<br>        // Quit the WebDriver<br>        if (driver != null) {<br>            driver.quit();<br>        }<br>    }<br>}</pre><p>In this example, TestClass1 contains two test methods (testMethod1 and testMethod2) that will be executed on the browsers specified in the TestNG XML file. The @Parameters annotation is used to receive the browser parameter from the XML file, and the @BeforeClass and @AfterClass annotations set up and tear down the WebDriver accordingly.</p><p>Similarly, create TestClass2, TestClass3, and TestClass4 with appropriate test methods and browser configurations.</p><p><strong>4. Run the Tests: </strong>Finally, you can run the tests using the TestNG test runner. Open a terminal or command prompt, navigate to the project’s root directory, and execute the following command:</p><pre>mvn test</pre><p>TestNG will read the TestNG XML file, identify the test groups, and execute the test methods on the corresponding browsers configured in the XML file. The tests will be distributed across the Docker containers running in Selenium Grid based on the specified browser parameters.</p><p>By configuring the TestNG XML file and using TestNG annotations, you can control which tests run on which Docker containers in Selenium Grid. The sample project and tests provided here demonstrate how to set up and execute tests on specific browsers in Selenium Grid with Docker.</p><p><strong>Maven project with JUnit as the testing framework</strong></p><ol><li><strong>Add Dependencies</strong>: In your Maven pom.xml file, add the following dependencies for JUnit and Selenium:</li></ol><pre>&lt;dependencies&gt;<br>    &lt;!-- JUnit --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>        &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;<br>        &lt;version&gt;5.8.0&lt;/version&gt;<br>        &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>        &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;<br>        &lt;version&gt;5.8.0&lt;/version&gt;<br>        &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Selenium --&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;org.seleniumhq.selenium&lt;/groupId&gt;<br>        &lt;artifactId&gt;selenium-java&lt;/artifactId&gt;<br>        &lt;version&gt;4.1.1&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>2.<strong> Create Test Classes</strong>: Create test classes that contain test methods. Each test class will contain test methods that are tagged with the desired browser using JUnit’s @Tag annotation.</p><p>Example test classes:</p><pre>import org.junit.jupiter.api.AfterAll;<br>import org.junit.jupiter.api.BeforeAll;<br>import org.junit.jupiter.api.Tag;<br>import org.junit.jupiter.api.Test;<br>import org.openqa.selenium.WebDriver;<br>import org.openqa.selenium.chrome.ChromeDriver;<br>import org.openqa.selenium.firefox.FirefoxDriver;<br><br>@Tag(&quot;chrome&quot;)<br>public class TestClass1 {<br>    private static WebDriver driver;<br><br>    @BeforeAll<br>    public static void setup() {<br>        System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;path/to/chromedriver&quot;);<br>        driver = new ChromeDriver();<br>    }<br><br>    @Test<br>    public void testMethod1() {<br>        // Test logic using the WebDriver<br>        // ...<br>    }<br><br>    @Test<br>    public void testMethod2() {<br>        // Test logic using the WebDriver<br>        // ...<br>    }<br><br>    @AfterAll<br>    public static void teardown() {<br>        // Quit the WebDriver<br>        if (driver != null) {<br>            driver.quit();<br>        }<br>    }<br>}</pre><p>In this example, TestClass1 contains two test methods (testMethod1 and testMethod2) that are tagged with @Tag(&quot;chrome&quot;). This indicates that these tests should run on the Chrome browser. The @BeforeAll and @AfterAll annotations are used to set up and tear down the WebDriver.</p><p>Similarly, create TestClass2, TestClass3, and TestClass4 with appropriate test methods and browser configurations, using the @Tag annotation to specify the desired browsers for each test class.</p><p>3. <strong>Run the Tests</strong>: To run the tests, you can use the JUnit test runner. Open a terminal or command prompt, navigate to the project’s root directory, and execute the following command:</p><pre>mvn test</pre><p>JUnit will execute the test methods in the test classes based on the specified browser tags. The tests will be distributed across the Docker containers running in Selenium Grid according to the specified browser tags.</p><p>By tagging the test methods with the desired browsers using JUnit’s @Tag annotation, you can control which tests run on which Docker containers in Selenium Grid. This allows you to distribute test execution across different browsers and platforms.</p><p><strong>Maven Surefire plugin</strong>:</p><p>If you’re using Maven, you can configure the Surefire plugin in your pom.xml file. Set the parallelization options, such as &lt;parallel&gt;classes&lt;/parallel&gt; or &lt;parallel&gt;methods&lt;/parallel&gt;.</p><pre>&lt;build&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;3.0.0-M5&lt;/version&gt; &lt;!-- Use the latest version available --&gt;<br>            &lt;configuration&gt;<br>                &lt;parallel&gt;classes&lt;/parallel&gt;<br>                &lt;threadCount&gt;4&lt;/threadCount&gt; &lt;!-- Number of parallel threads --&gt;<br>            &lt;/configuration&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>This configuration will run test classes in parallel using multiple threads.</p><ul><li>Command line execution: If you prefer running tests from the command line, you can use tools like Maven or JUnit’s command line runners. For example, with Maven, you can execute mvn test -Dtest=TestClass1,TestClass2 to run specific test classes in parallel.</li></ul><p>By following these steps, you can leverage Selenium Grid with Docker to execute your tests in parallel, maximizing the speed and efficiency of your test automation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c7839b58d7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Design Patterns]]></title>
            <link>https://medium.com/@ram.machavaram/software-design-patterns-cc17a589fc5?source=rss-2d71405a3700------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc17a589fc5</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[qa-testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[rest-api-automation]]></category>
            <category><![CDATA[restassured-java]]></category>
            <dc:creator><![CDATA[Ram]]></dc:creator>
            <pubDate>Wed, 31 May 2023 18:04:07 GMT</pubDate>
            <atom:updated>2023-06-04T16:22:08.643Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>For rest-assured Automation testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YUQKGaXHeKLsyyx97kBkpg.jpeg" /></figure><p>Design patterns are a powerful tool for improving reusability, maintainability, scalability, and readability in software development. Here’s a more efficient way of presenting the information.</p><p><strong>Automation Design Patterns:</strong></p><ol><li>Factory Design Pattern : Super class with multiple subclasses.</li><li>Page Object Model Pattern : Test cases, page classes, and page factory.</li><li>Facade Pattern : Multiple page classes and a single Façade Interface.</li><li>Fluent Page Object Model : Chaining actions on the page class.</li><li>Singleton Pattern : A single class object across the framework.</li></ol><blockquote>By utilizing these design patterns, you can enhance the overall quality of your codebase and make your automation framework more efficient.</blockquote><h4>Factory Design Pattern</h4><p>The Factory Design Pattern is a creational design pattern that provides an interface or superclass for creating objects, but allows subclasses or implementing classes to decide which objects to instantiate. In the context of REST Assured, the Factory Design Pattern can be used to create instances of RequestSpecification or Response objects based on different configurations or environments.</p><p>Benefits of using the Factory Design Pattern:</p><ul><li>Centralized object creation and configuration logic.</li><li>Enables encapsulation and decoupling of object creation from client code.</li><li>Allows for easy extensibility and flexibility when introducing new implementations or configurations.</li></ul><p>Implementation:</p><ol><li>Create an interface or abstract class representing the object to be created. In this case, it can be a RequestSpecification factory.</li><li>Define multiple concrete classes or subclasses that implement the factory interface or extend the abstract class. Each subclass can represent a different configuration or environment for creating RequestSpecification objects.</li><li>Create a factory class that encapsulates the object creation logic and returns the appropriate instance based on a provided configuration or condition.</li><li>Client code can then use the factory class to create instances of the RequestSpecification objects without having to know the specific implementation details.</li></ol><p>Example Code:</p><pre>import io.restassured.RestAssured;<br>import io.restassured.specification.RequestSpecification;<br><br>public interface RequestSpecFactory {<br>    RequestSpecification createRequestSpecification();<br>}</pre><pre>import io.restassured.RestAssured;<br>import io.restassured.specification.RequestSpecification;<br><br>public class DefaultRequestSpecFactory implements RequestSpecFactory {<br>    @Override<br>    public RequestSpecification createRequestSpecification() {<br>        return RestAssured.given()<br>                .baseUri(&quot;https://api.example.com&quot;)<br>                .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>                .log().all(); // Additional configurations<br>    }<br>}</pre><pre>import io.restassured.RestAssured;<br>import io.restassured.specification.RequestSpecification;<br><br>public class CustomRequestSpecFactory implements RequestSpecFactory {<br>    @Override<br>    public RequestSpecification createRequestSpecification() {<br>        return RestAssured.given()<br>                .baseUri(&quot;https://custom-api.example.com&quot;)<br>                .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>                .header(&quot;Authorization&quot;, &quot;Bearer &lt;token&gt;&quot;)<br>                .log().all(); // Additional configurations<br>    }<br>}</pre><pre>public class RequestSpecFactoryProvider {<br>    public static RequestSpecFactory getRequestSpecFactory(String environment) {<br>        if (&quot;default&quot;.equalsIgnoreCase(environment)) {<br>            return new DefaultRequestSpecFactory();<br>        } else if (&quot;custom&quot;.equalsIgnoreCase(environment)) {<br>            return new CustomRequestSpecFactory();<br>        } else {<br>            throw new IllegalArgumentException(&quot;Invalid environment: &quot; + environment);<br>        }<br>    }<br>}</pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        String environment = &quot;default&quot;; // or &quot;custom&quot;<br>        RequestSpecFactory requestSpecFactory = RequestSpecFactoryProvider.getRequestSpecFactory(environment);<br>        RequestSpecification requestSpec = requestSpecFactory.createRequestSpecification();<br><br>        // Use the created RequestSpecification for making API calls<br>        // For example:<br>        requestSpec.get(&quot;/users&quot;)<br>            .then()<br>            .statusCode(200)<br>            .extract()<br>            .response()<br>            .prettyPrint();<br>    }<br>}</pre><p>In the above example, we have an interface RequestSpecFactory that defines the method createRequestSpecification() for creating RequestSpecification objects. We have two concrete classes DefaultRequestSpecFactory and CustomRequestSpecFactory that implement this interface and provide different configurations for creating the RequestSpecification. The RequestSpecFactoryProvider class acts as a factory, returning the appropriate factory implementation based on the provided environment. Finally, in the Main class, we create an instance of the RequestSpecification using the factory, and then use it to make an API call.</p><p>By using the Factory Design Pattern, you can easily switch between different configurations or environments for creating RequestSpecification objects without modifying the client code. It promotes a modular and flexible approach to object creation and configuration in REST Assured.</p><h4>Page Object Model (POM) Pattern</h4><p>The Page Object Model (POM) Pattern is a design pattern that promotes the separation of UI elements and actions from test code. In the context of REST Assured, the POM Pattern can be adapted to encapsulate API endpoints, request parameters, and assertions into separate page classes.</p><p>Benefits of using the Page Object Model Pattern:</p><ul><li>Improved code reusability and maintainability by separating UI/API interactions from test code.</li><li>Enhanced readability and maintainability through encapsulation and abstraction of API-related logic.</li><li>Easy modification and maintenance of tests when API endpoints or request parameters change.</li></ul><p>Implementation:</p><ol><li>Identify the different API endpoints, request parameters, and assertions that are frequently used across your test suite.</li><li>Create a separate page class for each API endpoint or related functionality.</li><li>Define methods in the page classes that encapsulate the API operations, request parameters, and assertions.</li><li>Use the page classes in your test code to interact with the API endpoints and perform the required actions.</li></ol><p>Example Code:</p><pre>import io.restassured.RestAssured;<br>import io.restassured.response.Response;<br>import io.restassured.specification.RequestSpecification;<br><br>public class UserAPI {<br>    private static final String USERS_ENDPOINT = &quot;/users&quot;;<br>    private static final String SINGLE_USER_ENDPOINT = &quot;/users/{userId}&quot;;<br><br>    public static Response createUser(RequestSpecification requestSpec, String userJson) {<br>        return requestSpec.body(userJson)<br>                .post(USERS_ENDPOINT);<br>    }<br><br>    public static Response getUser(RequestSpecification requestSpec, int userId) {<br>        return requestSpec.pathParam(&quot;userId&quot;, userId)<br>                .get(SINGLE_USER_ENDPOINT);<br>    }<br><br>    // Add methods for update and delete operations as well<br>}</pre><pre>import io.restassured.RestAssured;<br>import io.restassured.specification.RequestSpecification;<br><br>public class Main {<br>    public static void main(String[] args) {<br>        RequestSpecification requestSpec = RestAssured.given()<br>                .baseUri(&quot;https://api.example.com&quot;)<br>                .header(&quot;Content-Type&quot;, &quot;application/json&quot;);<br><br>        // Creating a user<br>        String userJson = &quot;{\&quot;name\&quot;: \&quot;John Doe\&quot;, \&quot;email\&quot;: \&quot;john.doe@example.com\&quot;}&quot;;<br>        Response createUserResponse = UserAPI.createUser(requestSpec, userJson);<br>        createUserResponse.then()<br>                .statusCode(201);<br><br>        // Getting a user<br>        int userId = 1;<br>        Response getUserResponse = UserAPI.getUser(requestSpec, userId);<br>        getUserResponse.then()<br>                .statusCode(200)<br>                .extract()<br>                .response()<br>                .prettyPrint();<br>    }<br>}</pre><p>In the above example, we have a UserAPI class that encapsulates the API endpoints and their corresponding operations. The createUser() method is responsible for creating a user by making a POST request to the /users endpoint, and the getUser() method retrieves user details by making a GET request to the /users/{userId} endpoint.</p><p>In the Main class, we create a RequestSpecification object with common configurations using RestAssured. We then use the methods from the UserAPI class to interact with the API endpoints and perform the desired actions, such as creating a user and retrieving user details.</p><p>By using the Page Object Model Pattern, you can separate the API-related logic from the test code, promoting reusability, readability, and maintainability. Each page class represents a specific API functionality, and the methods within the page classes encapsulate the API operations, allowing for easy modification and maintenance of tests when endpoints or parameters change.</p><h4>Facade Pattern</h4><p>The Facade Pattern is a design pattern that provides a simplified interface to a complex subsystem. In the context of REST Assured, the Facade Pattern can be used to create a single interface that encapsulates multiple page classes or API endpoints, providing a simplified and unified way to interact with the API.</p><p>Benefits of using the Facade Pattern:</p><ul><li>Simplified and unified API interface, reducing the complexity and improving the readability of test code.</li><li>Encapsulation of the underlying complexities of the subsystem, making it easier to use and understand.</li><li>Enables easier maintenance and modification of the test code when there are changes in the API endpoints or underlying implementation.</li></ul><p>Implementation:</p><ol><li>Identify the different API endpoints or related functionality that can be grouped together.</li><li>Create a facade class that encapsulates the multiple page classes or API endpoints.</li><li>Define methods in the facade class that delegate the calls to the appropriate page classes or API endpoints.</li><li>Use the facade class in your test code to interact with the API, instead of directly using the individual page classes or endpoints.</li></ol><p>Example Code:</p><pre>import io.restassured.RestAssured;<br>import io.restassured.response.Response;<br>import io.restassured.specification.RequestSpecification;<br><br>public class UserFacade {<br>    private UserAPI userAPI;<br>    private ProfileAPI profileAPI;<br><br>    public UserFacade() {<br>        this.userAPI = new UserAPI();<br>        this.profileAPI = new ProfileAPI();<br>    }<br><br>    public Response createUser(RequestSpecification requestSpec, String userJson) {<br>        return userAPI.createUser(requestSpec, userJson);<br>    }<br><br>    public Response getUser(RequestSpecification requestSpec, int userId) {<br>        return userAPI.getUser(requestSpec, userId);<br>    }<br><br>    public Response updateProfile(RequestSpecification requestSpec, int userId, String profileJson) {<br>        return profileAPI.updateProfile(requestSpec, userId, profileJson);<br>    }<br><br>    // Add additional methods for other API operations<br>}</pre><pre>import io.restassured.RestAssured;<br>import io.restassured.specification.RequestSpecification;<br><br>public class Main {<br>    public static void main(String[] args) {<br>        RequestSpecification requestSpec = RestAssured.given()<br>                .baseUri(&quot;https://api.example.com&quot;)<br>                .header(&quot;Content-Type&quot;, &quot;application/json&quot;);<br><br>        UserFacade userFacade = new UserFacade();<br><br>        // Creating a user<br>        String userJson = &quot;{\&quot;name\&quot;: \&quot;John Doe\&quot;, \&quot;email\&quot;: \&quot;john.doe@example.com\&quot;}&quot;;<br>        Response createUserResponse = userFacade.createUser(requestSpec, userJson);<br>        createUserResponse.then()<br>                .statusCode(201);<br><br>        // Getting a user<br>        int userId = 1;<br>        Response getUserResponse = userFacade.getUser(requestSpec, userId);<br>        getUserResponse.then()<br>                .statusCode(200)<br>                .extract()<br>                .response()<br>                .prettyPrint();<br><br>        // Updating user profile<br>        String profileJson = &quot;{\&quot;city\&quot;: \&quot;New York\&quot;, \&quot;country\&quot;: \&quot;USA\&quot;}&quot;;<br>        Response updateProfileResponse = userFacade.updateProfile(requestSpec, userId, profileJson);<br>        updateProfileResponse.then()<br>                .statusCode(200);<br>    }<br>}</pre><p>In the above example, we have a UserFacade class that acts as a simplified interface to the complex subsystem consisting of UserAPI and ProfileAPI. The facade class delegates the calls to the appropriate methods in the underlying page classes.</p><p>In the Main class, we create an instance of the UserFacade and use its methods to interact with the API. Instead of directly using the individual page classes (UserAPI and ProfileAPI), we use the facade class, which provides a unified and simplified interface.</p><p>By using the Facade Pattern, you can encapsulate the complexities of multiple page classes or API endpoints into a single interface, providing a simpler and more readable way to interact with the API. It also allows for easier maintenance and modification of the test code, as changes in the underlying implementation can be handled within the facade class.</p><h4>Fluent Page Object Model (Fluent POM) Pattern</h4><p>The Fluent Page Object Model (Fluent POM) pattern is an extension of the Page Object Model (POM) pattern that aims to improve the readability and expressiveness of test code when interacting with REST APIs using REST Assured.</p><p><strong>Key Features:</strong></p><ol><li><strong>Method Chaining</strong>: The Fluent POM pattern leverages method chaining to perform multiple actions or assertions in a single line of code, resulting in more readable and concise code.</li><li>Fluent API Interface: Each method in the page class returns the page object itself, allowing for fluent and intuitive usage of methods.</li><li>Action and Assertion Methods: The page class contains methods that encapsulate API actions and assertions, providing a clear separation of concerns and improving code maintainability.</li></ol><p>Benefits of Using Fluent POM Pattern:</p><ul><li>Improved Readability: The method chaining syntax provides a more natural language-like flow, making the code easier to read and understand.</li><li>Concise Test Code: With fluent method chaining, multiple API actions or assertions can be performed in a single line, reducing code clutter and improving code maintainability.</li><li>Enhanced Expressiveness: The fluent interface of the pattern makes the test code more expressive, making it easier to convey the intent of the API interactions.</li></ul><p>Example Code:</p><pre>import io.restassured.RestAssured;<br>import io.restassured.response.Response;<br>import io.restassured.specification.RequestSpecification;<br><br>public class UserAPI {<br>    private static final String USERS_ENDPOINT = &quot;/users&quot;;<br>    private static final String SINGLE_USER_ENDPOINT = &quot;/users/{userId}&quot;;<br><br>    private RequestSpecification requestSpec;<br><br>    public UserAPI(RequestSpecification requestSpec) {<br>        this.requestSpec = requestSpec;<br>    }<br><br>    public UserAPI createUser(String userJson) {<br>        requestSpec.body(userJson)<br>                .post(USERS_ENDPOINT);<br>        return this;<br>    }<br><br>    public UserAPI getUser(int userId) {<br>        requestSpec.pathParam(&quot;userId&quot;, userId)<br>                .get(SINGLE_USER_ENDPOINT);<br>        return this;<br>    }<br><br>    // Add additional methods for other API operations<br><br>    public Response getResponse() {<br>        return requestSpec.extract().response();<br>    }<br>}<br></pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        RequestSpecification requestSpec = RestAssured.given()<br>                .baseUri(&quot;https://api.example.com&quot;)<br>                .header(&quot;Content-Type&quot;, &quot;application/json&quot;);<br><br>        UserAPI userAPI = new UserAPI(requestSpec);<br><br>        Response response = userAPI.createUser(&quot;{\&quot;name\&quot;: \&quot;John Doe\&quot;, \&quot;email\&quot;: \&quot;john.doe@example.com\&quot;}&quot;)<br>                .getUser(1)<br>                .getResponse();<br><br>        response.then()<br>                .statusCode(200)<br>                .extract()<br>                .response()<br>                .prettyPrint();<br>    }<br>}</pre><h4>Singleton Pattern</h4><p>The Singleton Pattern is a creational design pattern that ensures the existence of only one instance of a class and provides a global point of access to it. In the context of REST Assured, the Singleton Pattern can be used to create a single instance of the REST Assured configuration, allowing for efficient resource utilization and consistent behavior across tests.</p><p>Key Concepts:</p><ol><li>Private Constructor: The class implementing the Singleton Pattern should have a private constructor to prevent direct instantiation from outside the class.</li><li>Static Instance: The class should provide a static method that returns the single instance of the class.</li><li>Lazy Initialization: The instance of the class should be lazily initialized, i.e., created only when requested for the first time.</li><li>Thread Safety: The Singleton Pattern should handle multi-threaded environments properly to ensure thread safety.</li></ol><p>Example Code:</p><pre>import io.restassured.RestAssured;<br>import io.restassured.builder.RequestSpecBuilder;<br>import io.restassured.specification.RequestSpecification;<br><br>public class RestAssuredConfig {<br>    private static RestAssuredConfig instance;<br>    private RequestSpecification requestSpec;<br><br>    private RestAssuredConfig() {<br>        // Private constructor to prevent direct instantiation<br>        requestSpec = new RequestSpecBuilder()<br>                .setBaseUri(&quot;https://api.example.com&quot;)<br>                .setContentType(&quot;application/json&quot;)<br>                .build();<br>    }<br><br>    public static synchronized RestAssuredConfig getInstance() {<br>        if (instance == null) {<br>            instance = new RestAssuredConfig();<br>        }<br>        return instance;<br>    }<br><br>    public RequestSpecification getRequestSpecification() {<br>        return requestSpec;<br>    }<br>}<br></pre><pre>public class Main {<br>    public static void main(String[] args) {<br>        RestAssuredConfig config = RestAssuredConfig.getInstance();<br>        RequestSpecification requestSpec = config.getRequestSpecification();<br><br>        // Use requestSpec for making REST Assured calls<br>        // ...<br><br>        // Example usage<br>        requestSpec.get(&quot;/users&quot;)<br>            .then()<br>            .statusCode(200);<br>    }<br>}</pre><p>In this example, we use the RequestSpecBuilder class from REST Assured to create a more comprehensive request specification. The builder allows you to set various properties such as the base URI and content type.</p><p>The RestAssuredConfig class follows the Singleton Pattern as before, with a private constructor, a static getInstance() method, and a lazily initialized instance. The requestSpec property is now assigned using the RequestSpecBuilder to build the request specification.</p><p>In the Main class, we obtain the singleton instance of RestAssuredConfig using the getInstance() method and retrieve the request specification using the getRequestSpecification() method. The request specification can be used to make REST Assured calls.</p><p>Please note that this example assumes you have imported the necessary classes and dependencies for REST Assured. Make sure you have the required REST Assured libraries in your project to run the code successfully.</p><p>Remember to adapt the code to your specific requirements and add additional REST Assured functionalities as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc17a589fc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>