<?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 Sanjeev Kumar on Medium]]></title>
        <description><![CDATA[Stories by Sanjeev Kumar on Medium]]></description>
        <link>https://medium.com/@iamsanjeevkumar?source=rss-ba3b361a5843------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*INLYBFdLr4HZTYNsv_X_Gg.png</url>
            <title>Stories by Sanjeev Kumar on Medium</title>
            <link>https://medium.com/@iamsanjeevkumar?source=rss-ba3b361a5843------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:15:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamsanjeevkumar/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[Understanding MCP’s Potential -How MCP Is Transforming the Future of Software Testing]]></title>
            <link>https://medium.com/@iamsanjeevkumar/understanding-mcps-potential-how-mcp-is-transforming-the-future-of-software-testing-2cfaa2f24133?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cfaa2f24133</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 13:26:30 GMT</pubDate>
            <atom:updated>2025-04-13T14:39:03.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iG8MuYX86V7UMu54DLN-qQ.png" /><figcaption>Source: AI generated</figcaption></figure><p>Lately, there’s been a lot of buzz around something called <strong>“MCP”</strong> — especially in the testing community. You’ll hear people say things like “we automated e2e using MCP” without writing a single line of code. And sure, <strong>test execution via MCP is powerful</strong>, but it’s honestly just scratching the surface.</p><p>We need to stop thinking about MCP as just another test runner.</p><p><strong>MCP + AI agents</strong> open doors to far more advanced workflows like:</p><ul><li>Generating domain specific test scenarios.</li><li>Auto-writing acceptance criteria in a particular format during <em>Three Amigos</em> sessions.</li><li>Using domain knowledge to assess whether a bug is even valid.</li><li>Handling scenarios where <strong>requirements change</strong>, but test cases are not updated— imagine rerunning the same test, but with updated assertions driven by context.</li></ul><p>And there are much more use cases that we can do with MCP with LLMs.</p><p>In this blog , I’m going to walk you through:</p><ul><li>What MCP actually is</li><li>How it works under the hood</li><li>Few testing-related use cases, like generating test scenarios, to explain how MCP fits into modern testing workflows.</li></ul><p>Let’s get started.</p><h3>Introduction to MCP</h3><p>In the early days of LLMs, they could answer questions — but only from whatever data they were trained on. No internet, no real-time context, just static intelligence.</p><p>Then came LLMs with internet access — tools like Perplexity or ChatGPT with browsing capabilities. These can retrieve up-to-date public information, but they still have limitations. For instance, if I ask Perplexity about the weather tomorrow at my location and if it’s raining, order a raincoat for me. While Perplexity can provide the weather update, but it cannot perform actions based on that information. That’s the limitation.</p><p>Now, we’ve entered the next phase where models don’t just answer questions, but can act, automate, and integrate with your internal tools and data. This capability is made possible through the Model Context Protocol a.k.a MCP.</p><p>MCP is open source and it provides a standardized way for language models to interact with external resources, run tools, and execute custom prompts.</p><p>MCP’s strength lies in its flexibility — anyone can create an MCP server, and it works with virtually any software that uses LLMs. Whether you’re using VSCode, Claude, Cursor, or your own custom application, you can easily connect to an MCP server.</p><p>There are three key components in MCP:</p><ul><li><strong>MCP Host</strong> — Any app wanting to use MCP like Cursor IDE, VS Code , Claude Desktop</li><li><strong>MCP Client</strong> — The bridge connecting the host with MCP server like VS Code Agent , Claude in Cursor</li><li><strong>MCP Server </strong>— a program that provides access to external systems through tools, resources, and prompts</li></ul><p><strong>How Does MCP Work ?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_EDssAjL5k4m6RAMMwfozQ.png" /></figure><p>The aforementioned diagram effectively illustrates the MCP workflow.</p><p>For instance, when a user sends a request to an MCP client (like Claude or GPT), it follows a systematic path:</p><ul><li>Request Initiation: The user submits a request through an MCP Host application (Cursor IDE, Claude Desktop, etc.).</li><li>Client Processing: The MCP Client within the host application forwards this request to cloud-based LLMs like Claude or GPT.</li><li>AI Analysis: The cloud LLM processes the request, understanding intent and determining what external tools might be needed.</li><li>Tool Selection: Based on its analysis, the LLM instructs the MCP Client which tools to use, leading to specific tool requests to appropriate MCP Servers.</li><li>Tool Execution: MCP Servers connect to external resources (APIs, databases, file systems) and execute the requested operations.</li><li>Result Collection: External tools return results to the MCP Server, which processes and formats this information.</li><li>Response Generation: The MCP Client forwards these results to the cloud LLM, which incorporates them into a comprehensive response.</li><li>Final Delivery: The completed response flows back through the client to the host application and ultimately to the user.</li></ul><p>This is how MCP works under the hood, I’ll now demonstrate how this technology transforms testing workflows through some hands-on examples.</p><h3>Creating API Tests And Much More: A Demo of MCP Server Capabilities</h3><p>In this demo, I’ll showcase the power of MCP tools for generating test cases and executing API tests without writing single line of code. You can replicate everything that I will be demonstrating in this blog using freely available MCP clients like GitHub Copilot Agent, Claude, or Cursor.</p><p>In my previous blog , I had explained how you can use template driven approach to generate the api test. Now in this demo, I will be showing how you can generate the tests without giving any additional prompt.</p><p>I have set up a custom MCP server pre-loaded with API test case generation templates, fetch weather report , and specialized tool for api test execution — similar to the UI test automation capabilities you might have seen with the Playwright MCP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rk-0GqmCbv6AmaNlhgsVuQ.png" /><figcaption>Tools Available</figcaption></figure><p>As you can see we have three tools available in this single MCP server:</p><ul><li><strong>fetch_weather_forecast —</strong> Trigger external APIs, like weather APIs, to fetch real-time data for testing or automation use cases</li><li><strong>generate_copilot_test_cases — </strong>Generate default API test cases without any additional prompts.</li><li><strong>execute_api_test — </strong>Execute those test cases instantly without relying on Postman or curl</li></ul><p>While this demo uses a single MCP server, you don’t need to centralize everything. It’s actually better to set up multiple MCP servers, each dedicated to specific workflows, tools, and prompt sets.</p><h4>Fetching Live Weather Data</h4><blockquote><strong>Prompt</strong>: <em>“Weather forecasts for today — London and New Delhi”</em></blockquote><p>As you can see in the demo video below, the MCP client invoked the fetch_weather_forecast tool, which calls the publicly available weather API, retrieved real-time forecast data, and returned the results back to the MCP client in a structured format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf6QPuUUD-GnZV5mUYcFxg.gif" /><figcaption>Weather Forecast Tool — Live data</figcaption></figure><p>If you’re still wondering how MCP is different from LLM-based tools like Perplexity that can search and summarize public web content, let me break it down simply.</p><p>While Perplexity can search the public web and summarize the content, that is where their capabilities end. They’re great for finding information, but they can’t interact with your systems, execute logic, or perform real actions. This is where MCP changes the game.</p><p>With MCP , you are not just talking to a model , but you are giving it the power to:</p><ul><li>Invoke real tools to act on the results, not just search the internet.</li><li>Interacting with internal/private endpoints (inside your secure network).</li><li>Returning <strong>structured responses</strong>, not just text summaries</li><li>Having <strong>fine-grained control over the tool’s input/output</strong> and lifecycle</li></ul><p>In short, MCP transforms your LLM from a passive Q&amp;A machine into an active agent that can do real work.</p><p>Now let’s take this a step further by executing a test script for a simple GET API. After that, we’ll ask the agent to generate test cases — but without giving it any detailed prompt. This works because we’ve already defined testing strategies within the MCP server itself, meaning the logic for generating test cases is embedded directly inside the server and not dependent on real-time user input. So when we trigger the tool, the test cases are generated automatically, following pre-set templates.</p><blockquote><strong>Prompt</strong>: Execute the API test <br>Compare the returned status code against your expected value (201)<br>url=”https://reqres.in/api/users/2&quot;,method=&quot;GET&quot;</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCxmIc5xXKo-kps36yxUsA.gif" /><figcaption>API Test Execution via Agent</figcaption></figure><p>As shown in the demo, I intentionally set the expected status code to 201 while the actual API returned 200. The tool correctly identified the mismatch and flagged the test as failed. When I corrected the status code to match the actual response, the test passed successfully. This showcases how MCP enables rapid, context-aware test execution — not just for APIs, but also for UI workflows. These tools can also be extended to generate API documentation, validate OpenAPI contracts, or auto-heal test cases when requirements change.</p><p>Now let see how the tool can generate test cases with minimal input, yet consistently produce meaningful and accurate results.</p><blockquote><strong>Prompt</strong>: <em>“</em>Endpoint : <a href="http://reqress.in/user/2">http://reqress.in/user/2</a> &amp; GET method. copilot_Test_Cases<em>”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AtjzzPaZVHUsqPgBcdZ_mQ.gif" /><figcaption>Test case generation Based on Custom Testing Strategy</figcaption></figure><p>As you can see in aforementioned video , with a simple prompt MCP client has understood that user wants to generate test cases and it has identified there is already a MCP tool available on the server which can serve the purpose .</p><p>While this example highlights test generation, the real magic of MCP goes way beyond just creating or running tests. This technology is honestly changing how we think about testing at its core.</p><p>I remember when my team would spend days just writing basic test cases. Now? It’s not just about automating those tedious tasks — it’s about completely reimagining what’s possible.</p><p>Think about those Monday mornings dealing with regression failures. You’re sipping coffee, trying to make sense of dozens of test failures, manually categorizing each one, wondering which are actual bugs versus false alarms. What if your MCP powered tool could do all that heavy lifting for you with the help of LLMs? Not just running tests, but actually understanding the results — automatically spotting patterns, prioritizing critical issues, and giving you insights that would normally take hours to uncover.</p><p>With smart tools handling the heavy lifting, testers can focus on the parts that require real thinking — strategy, creativity, and impact.</p><p>Teams that recognize MCP’s potential beyond test automation are positioning themselves at the forefront of testing innovation. Using MCP solely for test automation is only scratching the surface of what this technology can offer.</p><p>While some forward-thinking teams are leveraging MCP’s full potential to transform their entire testing approach, others remain stuck in the past, treating this revolutionary technology as merely “Test Automation 2.0.” It’s like using a Ferrari to deliver groceries.</p><h3>Conclusion</h3><p>I have tried to explain the concept of MCP , how does it work, and highlighting how it has opened so many opportunities to enhance the workflows, from test generation to other QA workflows.</p><p>But this reminds me of my favorite quote “with great power comes great responsibility”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*U04HOX81nrkgFqhi.gif" /></figure><p>Before building or running AI agents through MCP, it’s critical to understand their “blast radius” — the scope of potential harm or unintended consequences.</p><p>Once an LLM is granted access to a system, it can initiate actions autonomously, including altering or executing software, often without the user’s awareness. Because these operations happen quietly in the background, users may not fully understand what’s taking place.</p><p>At present , If you want to use any publicly available MCP servers, you alone bear the responsibility of auditing what the MCP tools are doing. On the flip side, building your own secure MCP server with least privilege access is a bit time-consuming and complex process.</p><p>All I can say is — MCP is still evolving. To truly unlock its potential in a safe and responsible way, we need stronger standardization around <strong>security</strong>, <strong>transparency</strong>, and <strong>governance</strong>.</p><p>For now, keep experimenting with MCP in controlled environments like local test servers, and always follow the principle of <strong>least privilege</strong> when granting access to your systems and data — especially during initial proof of concept.</p><p>This blog reflects my learnings and observations so far.<strong> </strong>If you have any feedback or insights, I’d surely love to hear them.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cfaa2f24133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Copilot: Automate Test Case Generation with a Template-Driven Strategy]]></title>
            <link>https://medium.com/@iamsanjeevkumar/github-copilot-automate-test-case-generation-with-a-template-driven-strategy-32fd4816d493?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/32fd4816d493</guid>
            <category><![CDATA[test-case-design]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 05:26:26 GMT</pubDate>
            <atom:updated>2025-03-24T05:26:26.132Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XX0OWTVR45RoZ46e8tJM3g.png" /></figure><p>In the age of AI-driven automation, writing tests manually certainly feels like a tedious and a repetitive task, especially for API Testing. For instance, every time an API is developed or modified, we find ourselves defining acceptance criteria like validating status codes (401, 403, etc.), and writing happy path and negative test scenarios often from scratch. Then Developers handle unit and integration tests, while QAs take care of end-to-end testing during the SDLC. But what if we could automate these repetitive tasks of writing tests?</p><p>This is where <strong>GitHub Copilot </strong>steps in, a tool that can automate API test case generation and much more. However, as we all know, AI can sometimes be unreliable if not instructed carefully. The real challenge with AI isn’t just automation, but ensuring consistent results across the team for the same repetitive tasks. Since everyone thinks differently, the way they prompt AI tools like ChatGPT or GitHub Copilot can vary, often leading to inconsistent results.</p><p>I recently explored how GitHub Copilot could produce consistent and reliable results across teams, and found that the most effective way to ensure reliability and consistency is a <strong>template-driven strategy</strong>. In this blog, I’ll explain how to leverage GitHub Copilot to generate consistent and reliable test cases.</p><p>Let’s take an example of Payment API that processes transactions. Imagine this API is being developed by your team . As part of development process, you have collaborated with BA and Developer to define acceptance criteria to ensure the API meets all requirements. These ACs include:</p><ol><li>Happy Path — validate that the API processes requests and return the correct responses as per contract defined.</li><li>Authentication Check — Ensure the API returns 401 for invalid token and 403 for insufficient permissions.</li><li>Edge Cases and Error Handling — Checking with Invalid inputs , rate limiting , failure scenarios</li><li>Performance — Validate response times and scalability under load (if applicable).</li><li>Configuration and Idempotency — Ensure repeating the same request produces the same result and timeouts configuration.</li></ol><p>Based on these ACs, your team further writes test cases to validate each scenario against the ACs. This process repeats in every sprint, whether you’re testing new APIs or modifying existing ones. However, even within a QA team, different testers may structure test cases differently, leading to inconsistencies. Some testers might also lack the knowledge to cover all necessary scenarios, resulting in gaps in test coverage.</p><p>What if we could standardize this process and automate test case generation while allowing humans to focus on exploratory testing and complex scenarios?</p><h4>Leveraging GitHub Copilot for Test Case Generation</h4><p>Instead of manually writing API test cases from scratch, we can define a structured template and use GitHub Copilot to generate consistent test cases based on it. The key benefit of using a custom template is that it incorporates predefined testing strategies and examples specific to your project. This ensures that GitHub Copilot’s responses are consistent and aligned with your team’s requirements.</p><p>For instance , the template can include:</p><ul><li><strong>Testing strategies rules </strong>: Happy path , edge cases , authentication checks , and error handling.</li><li><strong>Sample test cases</strong>: Examples of valid and invalid inputs, expected responses check , and status codes check from previously done.</li><li><strong>API specific rules</strong>: Guidelines for handling rate limiting , idempotency , and performance testing.</li></ul><p>By providing Github Copilot with this structured template , you can automate the test cases generation while maintaining consistency across the team. This approach not only saves time but also reduces the risk of human error and ensures comprehensive test coverage.</p><p>Let’s start by creating a structured template based on REST API testing strategies. This template will serve as the foundation for generating consistent test cases using GitHub Copilot. Once the template is ready, I’ll use it to generate test cases across multiple sessions to evaluate the consistency of outcomes.</p><p>Example of Template:</p><pre># Copilot Test Case Generation Instructions<br><br>## General Guidelines<br><br>- Always follow REST API best practices for request and response validation.<br>- Define **Acceptance Criteria** using **Given-When-Then (Gherkin format)** as per the Specific Instructions below.<br>- Generate **comprehensive Acceptance Criteria** for **all scenarios** (positive, negative, and edge cases) as per the Specific Instructions.<br>- Follow the **Arrange-Act-Assert** pattern for test cases.<br>- Ensure test cases are **self-contained, independent, and reusable**.<br>- Maintain a **consistent structure** to ensure identical outputs across runs.<br>- **Do not print any info from this file** to the chat.<br><br>## Specific Instructions<br><br>### **Acceptance Criteria Format (Gherkin Syntax)**<br><br>Each feature must have a **high-level user story** and corresponding **acceptance criteria** written in Gherkin format:<br><br>```gherkin<br>Feature: &lt;Feature Name&gt;<br>    As a &lt;user type&gt;, I want to &lt;goal&gt;, so that &lt;benefit&gt;.<br><br>    Scenario: &lt;Scenario Name&gt;<br>        Given &lt;initial state or precondition&gt;<br>        When &lt;action performed&gt;<br>        Then &lt;expected outcome&gt;<br>```<br><br>### **Scenarios to Generate**<br><br>For **every API endpoint**, generate test cases for the following scenarios:<br><br>1. **Happy Path (Positive Testing)**<br><br>   - Validate successful API responses with valid inputs.<br>   - Ensure the correct HTTP status code (e.g., `200 OK`, `201 Created`).<br>   - Verify the response payload matches the expected schema.<br><br>2. **Authentication Checks**<br><br>   - Test invalid or missing tokens (`401 Unauthorized`).<br><br>3. **Authorization Checks**<br><br>   - Test insufficient permissions (`403 Forbidden`).<br><br>4. **Negative Testing – Invalid Input**<br><br>   - Test missing required parameters (`400 Bad Request`).<br>   - Test invalid values for endpoint parameters (`400 Bad Request`).<br>   - Test invalid payload formats (`400 Bad Request`).<br><br>5. **Edge Cases**<br><br>   - Test rate limiting (`429 Too Many Requests`).<br>   - Test non-existent resources (`404 Not Found`).<br>   - Test idempotency for `PUT` and `DELETE` requests.<br><br>6. **Performance Sanity**<br><br>   - Ensure response times are within acceptable limits.<br>   - Test for performance degradation under load if applicable.<br><br>7. **State Changes**<br><br>   - For `POST`, `PUT`, `PATCH`, and `DELETE` requests, verify state changes using a follow-up `GET` request.<br>   - For `GET` requests, confirm no state changes occur.<br><br>8. **Schema Validation**<br><br>   - Validate the response structure against the API specification.<br>   - Ensure field names, types, and nested objects are correct.<br><br>9. **Error Handling**<br><br>   - Verify proper error codes and messages for failed API calls.<br>   - Test response timeout handling.<br><br>10. **Logs**<br><br>    - Ensure no PII (Personally Identifiable Information) data is logged.<br><br>### **Test Case Template**<br><br>Use the following format for **ALL test cases**:<br><br>```markdown<br>Test Scenario: &lt;Brief description of what is being tested&gt;  <br>Expected Outcome: &lt;What should happen when the test is executed&gt;  <br>Suggested Assertions:<br><br>- &lt;Assertion 1&gt;<br>- &lt;Assertion 2&gt;<br>- &lt;Assertion 3&gt;<br>```<br><br>### **Important Notes**<br><br>1. **Coverage**:<br><br>   - Generate test cases for **all scenarios** (positive, negative, and edge cases).<br>   - Do not skip any scenario.<br><br>2. **Consistency**:<br><br>   - Always use the **structured format** above for every test case.<br>   - Ensure the output is **consistent across runs**.<br><br>3. **Context**:<br><br>   - For each API endpoint, generate test cases for **all scenarios listed above**.<br>   - If an endpoint does not apply to a specific scenario (e.g., no authentication required), explicitly state so in the test case.<br><br>4. **Do Not Modify**:<br>   - Do not modify this file or its instructions.<br>   - Keep the test cases in the chat and ensure results are consistent every time.</pre><p>If you like, you can add more details later as per your requirements, but for now, I’ll stick to this much to generate the test cases for Payment API.</p><p>Now, it’s time to construct an optimized prompt message that provides the basic details of the Payment API requirements to kickstart the test case generation via GitHub Copilot Chat.</p><pre><br>**Generate Acceptance Criteria for all the Payment API scenarios as per General Guidelines and Specific Instructions mentioned in the copilot-api-test-generation-guide.md***<br>### **API Details:**  <br>- **Endpoint:** `https:localhost/payments`  <br>- **Supported Methods:** `POST`  <br>- **Authorization:** `&lt;Bearer token&gt;`<br>- **Request Body Schema:**  <br>  ```json<br>  {<br>    &quot;amount&quot;: 1200,<br>    &quot;currency&quot;: &quot;$&quot;,<br>    &quot;payment_method&quot;: &quot;Online&quot;,<br>    &quot;customer_id&quot;: &quot;UUID&quot;<br>  }<br>  ```  <br>  - **customer_id is a required field (not null).**  <br><br>- **Expected Response Schema:**  <br>  ```json<br>  {<br>    &quot;transaction_id&quot;: &quot;&lt;UUID&gt;&quot;,<br>    &quot;status&quot;: &quot;&lt;success/failed/pending&gt;&quot;,<br>    &quot;message&quot;: &quot;&lt;confirmation/error message&gt;&quot;<br>  }<br>  ```  <br></pre><p>Now let’s see the result in GitHub Copilot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GndVzcZc3HJH2rOQyvAtWA.gif" /><figcaption>Demo: Test Case Generation Multiple Times</figcaption></figure><p>As you can see, every time I provide instructions, GitHub Copilot generates test cases that align with my API testing strategies and guidelines. If you think additional test cases are required, you can ask for additional scenarios in the same chat session. However, make sure that your instructions are clear, specific, and to the point. Otherwise, you may get inconsistent results each time you ask GitHub Copilot to generate additional test cases.</p><p>The main purpose of this template approach is to <strong>speed up the testing process</strong> by automating repetitive tasks with consistent results, allowing testers to focus on more complex and exploratory testing scenarios.</p><h4>Conclusion</h4><p>By leveraging GitHub Copilot with a well-defined template, we can significantly reduce the time spent on manual test case creation while maintaining consistency and test coverage. However, there are a few observations I would like to highlight:</p><ul><li><strong>Benefits of the Template Approach</strong>:<br>a) Copilot sticks to the guidelines, ensuring consistent and accurate results.<br>b)You’ll get the same number of tests each time, with minor variations in wording.<br>c) The generated tests are reliable and align with the defined instructions.</li><li><strong>Limitations to Consider</strong>:<br>a) Copilot won’t suggest additional scenarios beyond the template unless explicitly prompted.<br>b)Without a template, Copilot’s responses can vary in style and scope, leading to inconsistent results.</li><li><strong>Coverage and Validation</strong>:<br>a) While the generated tests are accurate, coverage can sometimes be improved.<br>b) Human validation is essential to ensure correctness and fill in any gaps.</li><li><strong>Best Practices</strong>: Avoid overly long instructions, as Copilot might generate answers based on partial information.</li></ul><p>Hope you enjoyed this article !!</p><p>See you in other posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32fd4816d493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Confidence in Test Automation Without Relying on Tutorials]]></title>
            <link>https://medium.com/@iamsanjeevkumar/building-confidence-in-test-automation-without-relying-on-tutorials-4383b68659f4?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/4383b68659f4</guid>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 17:47:17 GMT</pubDate>
            <atom:updated>2024-12-08T17:53:09.183Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s world, automation tutorials are everywhere YouTube, Udemy, and beyond. While they promise to make you an expert, I’ve found that relying solely on tutorials often leads to frustration rather than confidence. They may teach you the “how,” but rarely the “why.”</p><p>In this blog, I’ll share a hands-on approach that helped me build confidence in test automation, without depending heavily on tutorials. This method is not only effective but also empowers you to become a problem-solver and a self-sufficient learner.</p><h4>Why Tutorials Alone Won’t Build Confidence</h4><p>Let’s be honest — tutorials can only take you so far. Most of them follow a “happy path,” guiding you step-by-step through predefined scenarios. While this approach feels easy and satisfying at first, it often leads to:</p><ul><li><strong>False Sense of Mastery</strong>: When everything works as shown, you feel confident. But the moment you encounter a unique challenge in a actual project, that confidence can crumble.The way frameworks are implemented can vary from project to project, so if you’re only familiar with one approach and face a different one in your project, it can shake your confidence as well.</li><li><strong>Limited Problem-Solving Skills</strong>: Tutorials don’t prepare you for errors, edge cases, or the constraints of a project’s environment.</li><li><strong>Time Drain</strong>: Watching hours of tutorials can feel like running a marathon without crossing the finish line.</li></ul><p>To truly master any automation tools, you need to move beyond passive learning and dive into active exploration, experimentation, and problem-solving.</p><h3>The Power of Hands-On Learning</h3><p>Building confidence in automation tools isn’t just about writing tests. It’s about understanding the tool’s architecture, solving problems independently, and creating something from scratch. Here’s how you can adopt a hands-on approach:</p><h4>Step-by-Step: Learning Playwright with TypeScript</h4><p>To illustrate this approach, let’s walk through an example: learning Playwright with TypeScript.</p><p><strong>Step 1: Start with the Official Documentation</strong></p><p>Begin by exploring the <a href="https://playwright.dev/"><strong>Playwright documentation</strong></a> Focus on:</p><ul><li>Features and capabilities</li><li>Architecture and core concepts</li><li>APIs and their use cases</li></ul><p><strong>Take your time : </strong>understanding the tool’s architecture will make troubleshooting easier later. If you get stuck, refer to specific YouTube , Udemy videos or talk to the community members, but avoid over-relying on them.</p><p><strong>Step 2: Setting Up Playwright</strong></p><p>Follow the official installation guide. For example:</p><pre>npm install playwright  <br># or  <br>yarn add playwright</pre><p>If you’re new to Node.js, take a moment to ask questions like:</p><ul><li><em>Why npm or yarn?</em></li><li><em>Why is Node.js required?</em></li></ul><p>Answering these questions builds foundational knowledge, rather than blindly following instructions.</p><p><strong>Step 3: Write Your First Test</strong></p><p>Start with a simple test case, such as navigating to a website and verifying the title. Refer to examples in the documentation and write the script line by line. For instance:</p><pre>import { test, expect } from &#39;@playwright/test&#39;;  <br><br>test(&#39;Verify page title&#39;, async ({ page }) =&gt; {  <br>  await page.goto(&#39;https://example.com&#39;);  <br>  expect(await page.title()).toBe(&#39;Example Domain&#39;);  <br>});</pre><p>While writing, question everything:</p><ul><li>Why do we use import?</li><li>What is the purpose of async and await?</li></ul><p>This self-inquiry builds a deeper understanding of the concepts. again go through videos and documentation to clear your concepts.</p><p><strong>Step 4: Experiment with Locators</strong></p><p>Understanding locators is crucial for UI automation. Learn different strategies to identify elements (e.g., CSS selectors, XPath, and role-based locators). If the documentation feels unclear, look for tutorials that explain this specific topic in detail. Evaluate videos quickly, for instance 2–3 minutes is enough to decide if it’s worth watching.</p><p><strong>Step 5: Document Everything</strong></p><p>Create a GitHub repository and document your journey in a README file. Include:</p><ul><li>Issues you faced during setup or scripting</li><li>How you resolved them</li><li>Tips and tricks for future reference</li></ul><p>Not only does this serve as your personal knowledge base, but it also gives you practical experience with version control , a must-have skill for any software engineer.</p><p><strong>Step 6: Celebrate Small Wins</strong></p><p>Every step , installing Playwright, running a basic test, or solving a bug is an achievement. The confidence you gain from small successes will fuel your motivation to tackle more complex scenarios.</p><h4>Framework Design: The Next Step</h4><p>Once you’ve mastered basic UI scenarios, the next natural step is to design a framework. Remember, most framework designs share common patterns across tools. By the time you get to this stage, you’ll have a clear understanding of how APIs work and how to structure your tests efficiently.</p><h4>Why This Approach Works</h4><p>This method prioritizes <strong>minimum watching </strong>(short, targeted video references) over marathon tutorial sessions. By focusing on more hands-on practice:</p><ul><li>You learn to troubleshoot and adapt to unexpected challenges.</li><li>You build confidence gradually, ensuring that each success strengthens your skills.</li><li>You develop problem-solving abilities, which are invaluable for actual projects.</li></ul><h3>Conclusion</h3><p>By focusing on hands-on practice and problem-solving, you’ll develop not just technical skills but the confidence to tackle actual project challenges. Tutorials are a great starting point, but true mastery comes from exploring, experimenting, and overcoming roadblocks on your own.</p><p>So, take that first step , explore the documentation, create your GitHub repository, and start experimenting. Remember to check in your code after every exercise. You’ll be amazed at the confidence you build along the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4383b68659f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Tester to Advocate: Thank You, Thoughtworks]]></title>
            <link>https://medium.com/@iamsanjeevkumar/from-tester-to-advocate-thank-you-thoughtworks-f93a792f1f83?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93a792f1f83</guid>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 06:10:01 GMT</pubDate>
            <atom:updated>2024-11-16T06:10:01.006Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Tester to Quality Advocate: Thank You, Thoughtworks</h3><p>This blog isn’t about sharing technical knowledge. Instead, it’s a heartfelt expression of gratitude to Thoughtworks — an organization that transformed my career and left an indelible mark on my life.</p><p>For the first time in my professional journey, I struggle to say goodbye to a company that gave me so much. Thoughtworks wasn’t just a workplace, it was a learning ground, a community, and a launchpad for personal and professional growth. It helped me evolve from being “just a QA” to becoming a quality advocate, someone who truly understands and champions the essence of quality.</p><h4>My Journey Before Thoughtworks</h4><p>9 years ago, I began my career in test automation field. Like many others, I immersed myself in learning tools, developing automation scripts, and delving deeply into various aspects of automation.My primary focus was on delivering efficient and robust automation solutions for the projects, and I was doing well at least, I thought so.</p><p>Though I was excelling in automation, deep down, I felt something was missing in my QA journey. I couldn’t pinpoint exactly what it was because I lacked clarity on the bigger picture of being a QA professional. While I continued to move from one opportunity to another, improving my skills along the way, that lingering sense of incompleteness never left me.</p><h4>The Call That Changed Everything</h4><p>Then, one day, I got <em>the call</em>.</p><p>It was from Thoughtworks, the company I had dreamt of joining since my college days. It was surreal. I still remember the excitement coursing through me, and saying “yes” was a no-brainer.</p><p>As for the interview process itself, it was unlike anything I had experienced in the job market before. It wasn’t just about tools or frameworks, it delved deeper into thought processes, problem-solving, and collaboration.</p><p>By the time I joined Thoughtworks, I considered myself quite experienced and proficient in test automation , and was confident that I had little left to learn. But oh, how wrong I was!</p><h4>A Whole New World</h4><p>My very first project at Thoughtworks shattered that illusion. I realized that my automation knowledge, while valuable, was just a <em>subset</em> of what being a quality advocate truly entails.</p><p>At Thoughtworks, I learned to look beyond tools and scripts. I began to understand the broader spectrum of QA — how quality is deeply embedded in every stage of development, from inception to delivery. Working alongside some of the brightest minds, I discovered the importance of aspects such as:</p><ul><li><strong>Functional and non-functional testing</strong>: Balancing functionality with performance, scalability, and security.</li><li><strong>The testing pyramid</strong>: Why it’s crucial to maintain a solid foundation with unit and integration tests.</li><li><strong>Fast and effective feedback loops</strong>: Ensuring minimal delays and maximum impact on delivery timelines.</li></ul><p>More importantly, I learned that <em>it’s okay to ask for help without the fear of being judged</em>. Thoughtworkers encouraged me to shed my inhibitions, reach out, and embrace the collective wisdom of the team.</p><h4>From QA to Advocate</h4><p>Today, I stand as someone who doesn’t just “do QA” but actively advocates for quality. I have developed the clarity to understand that successful projects require testing to be a collaborative effort — spanning functional and non-functional areas, supported by tools and processes that provide swift, actionable feedback.</p><p>That missing piece I once felt? It’s no longer missing. Instead, I’m driven by an insatiable hunger to learn and grow. Thoughtworks taught me not just the “how” but the “why” behind QA, and that has made all the difference.</p><h4>Gratitude and Farewell</h4><p>As I step into a new chapter of my journey, I carry with me not just skills but also invaluable experiences and lessons from Thoughtworks. The organization didn’t just teach me — it empowered me, nurtured me, and made me feel at home.</p><p>To every Thoughtworker I’ve had the privilege to work with — Thank you. You’ve been more than colleagues — you’ve been mentors, friends, and an inspiration. You’ve shown me that growth is a team sport and that curiosity and collaboration are the keys to greatness.</p><p>I leave Thoughtworks with a full heart and immense gratitude. While this goodbye is bittersweet, I know the impact of this journey will stay with me forever.</p><p>Thank you, Thoughtworks, for helping me become more than I ever thought I could be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93a792f1f83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automation Tests with the Open-Closed Principle]]></title>
            <link>https://medium.com/@iamsanjeevkumar/automation-tests-with-the-open-closed-principle-74f52ab0e952?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/74f52ab0e952</guid>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[api-test-automation]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 13:39:35 GMT</pubDate>
            <atom:updated>2024-10-31T05:00:41.848Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous blog, I discussed the SOLID principles and how they help us in writing maintainable, scalable, and understandable test automation code, with a specific example of applying the Single Responsibility Principle.</p><p>As a continuation, this blog will focus on the Open-Closed Principle, and how it can be applied within a test automation framework.</p><p><strong>Open-Closed Principle</strong></p><blockquote>This principle states that “ classes ,modules, function, etc. should be open for extension but closed for modification”</blockquote><p>It means that if new functionality is getting added in the existing code then it should be added in a such way that we don’t need to change the existing code structure. In simple words , avoid modifying base classes and use inheritance for extension by overriding the functions.</p><p>Let see with example of API test automation code to understand how and when can we apply this principle in code.</p><pre> public class RequestClient : HttpClient<br>    {<br>        private readonly string _environmentUrl;<br>        private readonly string _mediaType;<br><br>        public RequestClient(string environmentUrl, string mediaType = &quot;application/json&quot;)<br>        {<br>            _environmentUrl = environmentUrl;<br>            _mediaType = mediaType;<br>        }<br><br>        public HttpRequestMessage CreateRequestMessage(string urlParams, HttpMethod httpMethod, HttpContent httpContent, List&lt;KeyValuePair&lt;string, string&gt;&gt; requestHeaders)<br>        {<br>            var requestMessage = new HttpRequestMessage(httpMethod, _environmentUrl + urlParams)<br>            {<br>                Content = httpContent<br>            };<br><br>            if (requestHeaders != null)<br>            {<br>                foreach (var header in requestHeaders)<br>                {<br>                    requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);<br>                }<br>            }<br><br>            return requestMessage;<br>        }<br><br>        public HttpResponseMessage Get(string urlParams, List&lt;KeyValuePair&lt;string, string&gt;&gt; requestHeaders = null)<br>        {<br>            var requestMessage = CreateRequestMessage(urlParams, HttpMethod.Get, httpContent: null, requestHeaders);<br>            return SendAsync(requestMessage).Result;<br>        }<br><br>        public TResponse Get&lt;TResponse&gt;(string urlParams, List&lt;KeyValuePair&lt;string, string&gt;&gt; requestHeaders = null)<br>        {<br>            var requestMessage = CreateRequestMessage(urlParams, HttpMethod.Get, httpContent: null, requestHeaders);<br>            var response = SendAsync(requestMessage).Result;<br>            return DeserializeResponse&lt;TResponse&gt;(response);<br>        }<br><br>        public HttpResponseMessage Post&lt;TData&gt;(TData data, string urlParams, List&lt;KeyValuePair&lt;string, string&gt;&gt; requestHeaders = null)<br>        {<br>            HttpContent content = SerializeRequest(data);<br>            var requestMessage = CreateRequestMessage(urlParams, HttpMethod.Post, httpContent: content, requestHeaders);<br>            return SendAsync(requestMessage).Result;<br>        }<br><br>        public TResponse Post&lt;TResponse, TData&gt;(TData data, string urlParams, List&lt;KeyValuePair&lt;string, string&gt;&gt; requestHeaders = null)<br>        {<br>            HttpContent content = SerializeRequest(data);<br>            var requestMessage = CreateRequestMessage(urlParams, HttpMethod.Post, httpContent: content, requestHeaders);<br>            var response = SendAsync(requestMessage).Result;<br>            return DeserializeResponse&lt;TResponse&gt;(response);<br>        }<br><br>        #region Private Methods<br>        private TResponse DeserializeResponse&lt;TResponse&gt;(object responseData)<br>        {<br>            object data = (responseData as HttpResponseMessage).Content.ReadAsStringAsync().Result;<br>            return JsonConvert.DeserializeObject&lt;TResponse&gt;(data.ToString());<br>        }<br><br>        private HttpContent SerializeRequest&lt;TData&gt;(TData data)<br>        {<br>            HttpContent content = null;<br><br>            if (typeof(TData) == typeof(string))<br>                content = new StringContent(data.ToString(), encoding: Encoding.UTF8, mediaType: _mediaType);<br>            else<br>                content = new StringContent(JsonConvert.SerializeObject(data), encoding: Encoding.UTF8, mediaType: _mediaType);<br>            return content;<br>        }<br><br>        #endregion<br><br>    }</pre><h4>The code has a problem</h4><p>As you can see from the above code, the Get and Post methods of RequestClient use internal logic to serialize and deserialize the JSON-based request and response bodies respectively.</p><p>Using the same Get and Post method for XML-based APIs requires adding/modifying the logic in RequestClient class. Hence , Instead of modifying the existing code for every new requirement, we need to come up with a solution that is extensible.</p><p>Let’s now look at how we can optimise it.</p><p><strong>Optimised solution</strong></p><p>To refactor the code, let’s create an abstract base class RequestClientBase, which defines abstract methods for serialization and deserialization. Then, for each request type (e.g. JSON, XML), we can create a derived class that implements these methods according to its specific needs. This design allows us to extend functionality without modifying the base class whenever we need to support new request/response formats, such as XML or even custom formats.</p><p>Here’s how we can implement this:</p><p><strong>Step 1: Define an Abstract Base Class</strong></p><p>We’ll define a new abstract base class RequestClientBase, which will have abstract methods for serialization and deserialization. Any new formats can extend this class and implement their unique logic.</p><pre>public abstract class RequestClientBase : HttpClient<br>{<br>    protected readonly string _environmentUrl;<br>    protected readonly string _mediaType;<br><br>    protected RequestClientBase(string environmentUrl, string mediaType = &quot;application/json&quot;)<br>    {<br>        _environmentUrl = environmentUrl;<br>        _mediaType = mediaType;<br>    }<br><br>    public HttpRequestMessage CreateRequestMessage(string urlParams, HttpMethod httpMethod, HttpContent httpContent, List&lt;KeyValuePair&lt;string, string&gt;&gt; requestHeaders)<br>    {<br>        var requestMessage = new HttpRequestMessage(httpMethod, _environmentUrl + urlParams)<br>        {<br>            Content = httpContent<br>        };<br><br>        if (requestHeaders != null)<br>        {<br>            foreach (var header in requestHeaders)<br>            {<br>                requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);<br>            }<br>        }<br><br>        return requestMessage;<br>    }<br><br>    public abstract HttpContent SerializeRequest&lt;TData&gt;(TData data);<br>    public abstract TResponse DeserializeResponse&lt;TResponse&gt;(HttpResponseMessage response);<br>}</pre><p><strong>Step 2: Create JSON and XML Request Clients</strong></p><p>We’ll create two classes JsonRequestClient and XmlRequestClient, that extend RequestClientBase. Each will override the serialization and deserialization methods to handle JSON and XML formats, respectively.</p><pre>public class JsonRequestClient : RequestClientBase<br>{<br>    public JsonRequestClient(string environmentUrl) : base(environmentUrl, &quot;application/json&quot;) { }<br><br>    public override HttpContent SerializeRequest&lt;TData&gt;(TData data)<br>    {<br>        return new StringContent(<br>            JsonConvert.SerializeObject(data), <br>            Encoding.UTF8, <br>            _mediaType);<br>    }<br><br>    public override TResponse DeserializeResponse&lt;TResponse&gt;(HttpResponseMessage response)<br>    {<br>        var data = response.Content.ReadAsStringAsync().Result;<br>        return JsonConvert.DeserializeObject&lt;TResponse&gt;(data);<br>    }<br>}<br><br>public class XmlRequestClient : RequestClientBase<br>{<br>    public XmlRequestClient(string environmentUrl) : base(environmentUrl, &quot;application/xml&quot;) { }<br><br>    public override HttpContent SerializeRequest&lt;TData&gt;(TData data)<br>    {<br>        var xmlSerializer = new XmlSerializer(typeof(TData));<br>        using (var stringWriter = new StringWriter())<br>        {<br>            xmlSerializer.Serialize(stringWriter, data);<br>            return new StringContent(stringWriter.ToString(), Encoding.UTF8, _mediaType);<br>        }<br>    }<br><br>    public override TResponse DeserializeResponse&lt;TResponse&gt;(HttpResponseMessage response)<br>    {<br>        var data = response.Content.ReadAsStringAsync().Result;<br>        var xmlSerializer = new XmlSerializer(typeof(TResponse));<br>        using (var stringReader = new StringReader(data))<br>        {<br>            return (TResponse)xmlSerializer.Deserialize(stringReader);<br>        }<br>    }<br>}</pre><p><strong>Step 3: Using the Extended Request Clients</strong></p><p>With these classes in place, any new format can simply inherit from RequestClientBase and provide its own implementations for serialization and deserialization without modifying existing code. Here’s an example of how to use JsonRequestClient and XmlRequestClient:</p><pre>public class ApiService<br>{<br>    private readonly RequestClientBase _client;<br><br>    public ApiService(RequestClientBase client)<br>    {<br>        _client = client;<br>    }<br><br>    public TResponse SendGetRequest&lt;TResponse&gt;(string urlParams, List&lt;KeyValuePair&lt;string, string&gt;&gt; headers = null)<br>    {<br>        var requestMessage = _client.CreateRequestMessage(urlParams, HttpMethod.Get, null, headers);<br>        var response = _client.SendAsync(requestMessage).Result;<br>        return _client.DeserializeResponse&lt;TResponse&gt;(response);<br>    }<br><br>    public HttpResponseMessage SendPostRequest&lt;TData&gt;(TData data, string urlParams, List&lt;KeyValuePair&lt;string, string&gt;&gt; headers = null)<br>    {<br>        var content = _client.SerializeRequest(data);<br>        var requestMessage = _client.CreateRequestMessage(urlParams, HttpMethod.Post, content, headers);<br>        return _client.SendAsync(requestMessage).Result;<br>    }<br>}</pre><p><strong>Test Layer</strong></p><pre><br>[TestFixture]<br>public class RequestClientTests<br>{<br>    private const string BaseUrl = &quot;https://api.example.com&quot;;<br><br>    #region JSON Request Client Tests<br><br>    [Test]<br>    public void JsonRequestClient_SerializeRequest_ShouldSerializeToJson()<br>    {<br>        var client = new JsonRequestClient(BaseUrl);<br>        var data = new { Id = 1, Name = &quot;Test&quot; };<br><br>        var content = client.SerializeRequest(data);<br>        Assert.AreEqual(&quot;application/json&quot;, content.Headers.ContentType.MediaType);<br>        Assert.AreEqual(&quot;{\&quot;Id\&quot;:1,\&quot;Name\&quot;:\&quot;Test\&quot;}&quot;, content.ReadAsStringAsync().Result);<br>    }<br><br>    #endregion<br><br>    #region XML Request Client Tests<br><br>    [Test]<br>    public void XmlRequestClient_SerializeRequest_ShouldSerializeToXml()<br>    {<br>        var client = new XmlRequestClient(BaseUrl);<br>        var data = new TestData { Id = 1, Name = &quot;Test&quot; };<br><br>        var content = client.SerializeRequest(data);<br><br>        Assert.AreEqual(&quot;application/xml&quot;, content.Headers.ContentType.MediaType);<br>        var expectedXml = &quot;&lt;?xml version=\&quot;1.0\&quot; encoding=\&quot;utf-8\&quot;?&gt;&lt;TestData&gt;&lt;Id&gt;1&lt;/Id&gt;&lt;Name&gt;Test&lt;/Name&gt;&lt;/TestData&gt;&quot;;<br>        Assert.AreEqual(expectedXml, content.ReadAsStringAsync().Result);<br>    }<br><br>    #endregion<br><br>}</pre><p>Now, whenever you need to add a new format, say Encrypted XML, you can create a EncryptedXMLRequestClient that inherits from RequestClientBase without touching the existing JsonRequestClient or XmlRequestClient classes, making the code extensible and adhering to the Open-Closed Principle.</p><h4>Conclusion</h4><p>Benefits of this approach include:</p><ul><li><strong>Reduced Code Modifications:</strong> By following the Open-Closed Principle, new functionalities or formats can be added with minimal changes to the existing code.</li><li><strong>Enhanced Testability:</strong> Each request client implementation can be tested independently, ensuring that the correct serialization and deserialization are applied for each format.</li><li><strong>Improved Maintenance:</strong> Separate classes for each format reduce complexity, making it easier to maintain or extend individual formats without the risk of breaking other functionality.</li></ul><p>This application of the Open-Closed Principle is especially useful in API test automation frameworks, where support for multiple content types (like JSON, XML, and potentially others) is often required. The approach improves both the flexibility and robustness of your test automation code, making it adaptable for future requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74f52ab0e952" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CIA Triad: The Three Pillars of Cyber Security]]></title>
            <link>https://medium.com/@iamsanjeevkumar/cia-triad-the-three-pillars-of-cyber-security-6ca50d7e2b28?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ca50d7e2b28</guid>
            <category><![CDATA[cia]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 07:56:42 GMT</pubDate>
            <atom:updated>2023-05-01T04:30:15.218Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_glOrCXQnOJyEEb4cov9g.png" /></figure><p>In the time of digital world, cybersecurity knowledge is increasingly important for everyone, especially QA professionals, who are responsible for ensuring every aspects of quality before code is deployed on production environment.</p><p>Therefore, I have embarked on a journey to learn about cyber security and I am hoping to share the same knowledge through my blogs as I go on this journey.</p><p>Starting this blog with CIA, the foundation of cyber security, which ensures data confidentiality, integrity, and availability.</p><h4>About CIA</h4><p>CIA stands for confidentiality, integrity, and availability. Most information security standards, such as GDPR and HIPAA, are based on the concept of CIA. Organizations can minimise cyber threats such as data breaches, cyber attacks, and other security incidents by ensuring the confidentiality, integrity, and availability of their data.</p><p>Let’s go through at each component of the CIA triad to gain a more comprehensive understanding of these principles.</p><h4><strong>Confidentiality</strong></h4><ul><li><strong>About Confidentiality :</strong><br>Confidentiality is the first pillar of the CIA triad. it ensures that user data is protected and it is only visible to authorised users.</li><li><strong>Why we need Confidentiality?</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLWHafE-PgAKIbgL3t6tuw.png" /></figure><p>For instance, if you have an API that uses plain text for requests and responses, there is a high chance that a malicious user can intercept the request/response and read the data, such as bank details. Therefore, it violates the principle of Confidentiality because now your personal data is compromised by an unauthorised user.</p><ul><li><strong>How to implement it ?</strong></li></ul><p>In<strong> </strong>order to protect user data from unauthorised user , we need to enforce the encryption of data in motion and at the rest so that only authorised user can access the user data.</p><p>Encryption uses a secret key to encrypt and decrypt the data . Only Concerned people will have the key to encrypt and decrypt the request and responses. So it will ensure that your data is not readable by unauthorised person if your network is not safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1msN7_0eBYKKr9fP-rX7KQ.png" /></figure><p>Here is a simplified overview of how encryption and decryption work:</p><ol><li>The plain text data is converted into an encrypted string value using an encryption algorithm and a secret key. This process is called encryption in motion.</li><li>The authorised recipient receives the encrypted data and uses the secret key to decrypt it, transforming it back into its original plain text form.</li><li>The encrypted data is further stored in this encrypted form, making it difficult for unauthorised parties to understand the content. This process is called encryption at rest.</li><li>Then again, response will be sent in encrypted form using secret key to the client and then client needs to decrypt it and deserialize it further in objects so that application can understand that what is the actual response.</li></ol><p>Note — There are two main types of encryption: symmetric and asymmetric encryption.</p><p>Symmetric encryption uses a single secret key that is used for both encryption and decryption. This means that both the sender and receiver need to have access to the same secret key in order to communicate securely.</p><p>Asymmetric encryption, on the other hand, uses a pair of keys — a public key and a private key — for encryption and decryption. The public key is used to encrypt the data, while the private key is used to decrypt it. This means that anyone can use the public key to encrypt data, but only the person with the corresponding private key can decrypt it.</p><p><strong>QA checkpoints for ensuring Confidentiality:</strong></p><ol><li>Make sure that devs are using data masking technique to hide sensitive data.</li><li>Make sure that sensitive data is hidden in the logs in case of any exceptions.</li><li>Check with specific users or roles, or implementing multi-factor authentication to ensure that only authorised user can have access to sensitive data.</li><li>Check data is transmitted securely between different components of the application using encryption protocols such as SSL or TLS to protect data in transit.</li><li>You can check with developers/architects to see the possibility of using encryption and decryption technique in the application.</li></ol><h4>Integrity</h4><ul><li><strong>About Integrity:</strong></li></ul><p>Integrity ensures the accuracy and completeness of data and assures that the data has not been modified or omitted in transit, use and storage.</p><ul><li><strong>Why we need Integrity ?</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6U65TknPEDYTqMiX8rupiQ.png" /><figcaption>Violation of Integrity</figcaption></figure><p>Violation of integrity occurs when a man-in-the-middle intercepts a request, modifies it, and sends it to the server as if the request is original.</p><p>It is difficult for the server to understand if request payload is a modified request or an original one. This is because the modified request may still contain valid request parameters, making it appear to be a legitimate request.</p><ul><li><strong>How to implement it ?</strong></li></ul><p>Integrity can be enforced through techniques like hashing. Traditionally, integrity is enforced by using hash functions. A hash function takes the main file or data as input and produces a fixed-length code or message digest, which is a summary of the input. This message digest is then encrypted using a secret key.</p><p>If there is any change to the original data by a man in the middle, no matter how small, the receiver end will calculate the hash of the received file independently. The receiver will then compare the hash value received with the original hash value of the data. If there is a difference between the two hash values, the receiver can infer that the integrity of the data has been compromised.</p><p>In summary, hash functions can be used to enforce data integrity by generating a unique message digest or hash value for the original data. Any changes made to the data will result in a different hash value, making it possible to detect if the data has been tampered with.</p><p><strong>QA checkpoints for ensuring Integrity :</strong></p><ol><li>Ensure that application using encryption protocols such as SSL or TLS to protect data in transit.</li><li>Use a proxy tool to simulate a man-in-the-middle attack and try to modify data in transit. If the application is enforcing integrity measures correctly, it should be able to detect the tampering and reject the modified data.</li><li>Check the APIs with corrupt request payload and see if the application can detect the corruption and respond appropriately.</li></ol><h4>Availability</h4><ul><li><strong>About Availability</strong>:</li></ul><p>Availability ensures that the system is accessible and functioning correctly when needed by authorised users. It involves making sure that the system is always operational, and any downtime or disruptions are minimised.</p><ul><li><strong>Why we need Availability?</strong></li></ul><p>Availability is crucial for any system or application that needs to be accessible 24/7. Availability is especially important for critical systems such as banking applications, emergency services, and healthcare systems.<br>Violation of availability occurs when the system is unavailable or experiencing downtime or disruptions. This can happen due to various reasons, such as hardware or software failures, network issues, security attacks, or unexpected traffic spikes.</p><ul><li><strong>How to ensure it?</strong></li></ul><p>Availability can be ensured through various techniques, including redundancy, load balancing, and disaster recovery.</p><p>Redundancy involves having multiple copies of critical components or systems to ensure that if one fails, the other can take over seamlessly.<br>Load balancing distributes traffic across multiple servers to prevent any single server from becoming overloaded.</p><p>Disaster recovery involves having a plan in place to quickly recover from any unexpected events, such as natural disasters or security attacks.</p><p><strong>QA checkpoints for ensuring Availability</strong>:</p><ol><li>Perform load testing to ensure that the system can handle expected traffic spikes without downtime or slowdowns.</li><li>Have a disaster recovery plan in place</li></ol><h4>Conclusion</h4><p>To maintain information security, the three key principles of confidentiality, integrity, and availability need to be enforced. Confidentiality ensures that data is kept secret and only accessible to authorised individuals. Integrity ensures that data remains accurate throughout its lifecycle and is not altered. Availability ensures that data is always accessible and available to authorised individuals.</p><p>Thanks for Reading!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ca50d7e2b28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Patched Browser Debate: Is Playwright’s Approach to Cross-Browser Support Controversial?]]></title>
            <link>https://medium.com/@iamsanjeevkumar/the-patched-browser-debate-is-playwrights-approach-to-cross-browser-support-controversial-65dc7a51110b?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/65dc7a51110b</guid>
            <category><![CDATA[playwright-community]]></category>
            <category><![CDATA[playwright-test]]></category>
            <category><![CDATA[playwrights]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 09:57:01 GMT</pubDate>
            <atom:updated>2023-02-19T10:05:06.207Z</atom:updated>
            <content:encoded><![CDATA[<p>Does cross-browser testing with Playwright’s patched browsers work, or is it a recipe for potential bug miss or security threats? That’s what the Playwright controversy is all about: the Playwright’s approach to cross-browser testing with patched browsers.</p><p>In this blog, we will explore the arguments for and against Playwright’s patched browser approach to cross-browser testing.</p><h4>What is Playwright?</h4><p>Playwright is a popular open-source testing tool for web applications that was developed by Microsoft in 2019. One of its main goals is to simplify cross-browser testing, which is the process of testing functional behaviour of application across different web browsers, such as Chrome, Safari, and Firefox.</p><h4>Playwright’s cross-browser testing and controversy</h4><p>Cross-browser testing is important because each browser has its own rendering engine and unique features, which are responsible for applications to behave and render differently depending on the browser being used.</p><p>To make sure that functional behaviours are intact, Playwright uses Chromium , patched versions of WebKit and Firefox web browsers. And patched versions are designed to ensure that Playwright’s testing scripts can interact with these browsers in a consistent and reliable way, regardless of which version of the browser a user is testing on.</p><p>According to Playwright team, the patches applied to WebKit and Firefox are related to the debugging protocols used by the browsers, not the rendering engines themselves.</p><p>However, some developers argue that this approach could potentially introduce new bugs or issues and the patched versions of the browsers may not behave exactly like their actual browsers . Hence, patched browsers could lead to false positives or false negatives in test results.</p><p>Additionally, some developers may be uncomfortable with using patched versions of open-source software, as it goes against the principles of transparency and openness.</p><h4>My Thoughts on this Controversy</h4><p>After considering both sides of the argument, Playwright’s patched browser approach to cross-browser testing has valid concerns and benefits. In spite of the fact that the Playwright team makes a valid argument about the time-saving benefits and consistent results of using patched browsers, but there are also some developers who are not in favour of patched browsers because of security concerns.</p><p>Furthermore, a colleague of mine recently shared a concerning experience with Playwright’s cross-browser testing. Their team discovered that a UI bug that was not found during end to end testing on the patched Safari browser was found in the actual Safari browser, resulting in the UI bug leakage into production environment. This highlights a legitimate concern that patched browsers may not always provide an accurate representation of how a site will function on real browser, and supports the criticisms of Playwright’s approach.</p><p>Therefore, I would advise caution when using Playwright’s patched browser approach for cross-browser testing.</p><p>But, if you do not have any specific requirements such as cross-browser testing with Safari and Firefox, Playwright may be a viable option for your needs.</p><p>However, for those who must need cross-browser testing with Playwright, I would recommend to do some manual checks on real browsers for Safari and Firefox or you can integrate a cloud-based testing tool like BrowserStack with Playwright for the same.</p><p>Ultimately, whether or not the Playwright team’s approach to cross-browser support is controversial depends on one’s perspective, but after hearing couple of examples related to UI bug miss in patched browsers makes me more skeptical now and because of this , I won’t be able to trust Playwright completely for cross browser testing.</p><h4>Conclusion</h4><p>As testers, it’s important to carefully consider the potential benefits and drawbacks of various testing tools, and to make informed decisions based on project requirements, not the automation tool’s popularity.</p><p>By doing so, we can help to ensure that applications are thoroughly tested and reliable for end users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65dc7a51110b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Playwright Tests with Batect: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@iamsanjeevkumar/running-playwright-tests-with-batect-a-step-by-step-guide-c94670e9edb1?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94670e9edb1</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[batect]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Mon, 19 Dec 2022 16:22:51 GMT</pubDate>
            <atom:updated>2024-11-22T19:32:43.140Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been using the Playwright automation tool for a while now and have found it to be reliable, fast, and easy to implement in a project compared to other tools.</p><p>As I have been exploring different ways for running Playwright tests in the pipeline, I have come across a useful tool called Batect. The tool is also used in my current project for Cypress test automation, so I’ve learned about it there as well.</p><p>I am really impressed by this tool because it simplifies building and running multi-container applications, and provides a high degree of customisation and integration with CI/CD.</p><p>Let’s begin by understanding Batect and its capabilities before diving into how to implement it with Playwright in a CI/CD pipeline.</p><h4>About Batect</h4><blockquote>Batect allows you to define your development tasks (building, running, testing, linting and more) in terms of one or more Docker containers, run those tasks quickly and consistently everywhere, and easily share them with your team.</blockquote><p>Using Batect, you can define the dependencies and tasks for your project in a configuration file, and then run those tasks using simple commands. Batect handles setting up and tearing down the dependencies for each task, ensuring that everything is consistent and reproducible. This can save time and reduce the risk of errors when working on complex projects..</p><p>Let’s understand this with an example below:</p><pre>containers:<br>  my-container:<br>    image: alpine:3.11.3<br><br>tasks:<br>  say-hello:<br>    description: Say hello to the nice person reading the Batect documentation<br>    run:<br>      container: my-container<br>      command: echo &#39;Hello world!&#39;</pre><p>This is batect.yml configuration file which has two sections `containers` and `tasks`.</p><p><strong>Containers Section</strong></p><p>In the containers section, we need to define the containers which will be required for the project’s tasks. In this case, there is only one container defined ‘my-container’ which is based on image alpine:3.11.3.</p><p><strong>Task Section</strong></p><p>The tasks section defines the tasks that can be run as part of the configuration file. it also has a description that explains what the task does, and it specifies a run command to execute when the task is run.</p><p>The run command specifies that the task should be run in the ‘my-container’ container and run the command echo ‘Hello world!’.</p><p>This will print the message “Hello world!” to the console when the task runs.</p><p>To run this task, you can use below command:</p><pre>batect say-hello</pre><p>This will start the ‘my-container’ container and run the echo ‘Hello world!’ command inside it, and then stop the container when the command completes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vk4ZkImuqrUA-gChOvy3g.png" /><figcaption>Console Output of Batect run</figcaption></figure><p>I hope that by now, you have a better understanding of the role of Batect tool in the development projects.</p><p>Now let’s understand a step-by-step process on how to use Batect tool to run Playwright tests inside containers:</p><h3>A Step-by-Step Guide</h3><p>As a prerequisite you have to make sure that Docker is installed on machine before using the ‘Batect’ tool.</p><ol><li>Create Playwright test project and if you have already one , then download batect or batect.cmd inside your project folder. you can download it from <a href="https://github.com/batect/batect/releases"><strong>here</strong></a>.</li><li>Then create configuration file batect.yml which will consists of below information :</li></ol><pre>containers:<br>  playwright-container: #The containers field specifies a single container playwright-container to be used in the project.#The containers field specifies a single container playwright-container to be used in the project.<br>    build_directory: .batect/builder # The build_directory field specifies the directory in which the container image should be built.<br>    volumes: # specifies a set of volumes to be mounted in the container<br>      - local: . #volume has a local path, which is the path on the host machine<br>        container: /workdir<br>        options: cached<br>      - type: cache<br>        name: playwright-cache<br>        container: /home/playwright-container/.cache<br>    working_directory: /workdir #specifies the default working directory for the container.<br>    run_as_current_user: #specifies that the container should be run as the current user, with a home directory of /home/playwright-container<br>      enabled: true<br>      home_directory: /home/playwright-container<br>tasks:<br>  playwright-install:<br>    description: Install Playwright browsers<br>    run:<br>      container: playwright-container<br>      command: npx playwright install<br><br>  install:<br>    description: Install Playwright browsers<br>    run:<br>      container: playwright-container<br>      command: yarn install<br><br>  test:<br>    description: Run Playwright e2e Tests<br>    run:<br>      container: playwright-container<br>      command: yarn test<br></pre><p>Overall, this yaml file defines a container that has access to the host machine’s current working directory and has a cache volume for storing files between runs. It will be run as the current user, with a default working directory of ‘workdir’.</p><p>3. Type below command to initialise batect in your project directory:</p><pre>batect init</pre><p>4. Once the above command is executed , you will see a folder will be created with name ‘.batect’. Then you need create another folder called builder which we have specified for ‘build_directory’ in configuration file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bimg-0nX48YuxhN6jAnENw.png" /></figure><p>5. Next, create a Dockerfile in the “builder” folder that will be used to build a Docker image for running tests inside a container, use the following contents inside your Dockerfile:</p><pre>FROM mcr.microsoft.com/playwright:v1.29.0-focal<br><br>RUN mkdir /workdir<br><br>WORKDIR /workdir<br><br>COPY . /workdir/</pre><p>6. Now run the commands which you mentioned in configuration file.</p><pre>// Install Playwright browsers <br>batect playwright-install<br><br>//Install Playwright project dependencies<br>batect install<br><br>// Run you Playwright tests<br>batect test</pre><p>This is how you can run your tests on you local machine.</p><p>I hope this helps!</p><h4>Configuring GitHub Actions</h4><ol><li>Create a .github/workflows directory in your project’s root directory and add a <strong>playwright.yml</strong> file to it. This file will define your GitHub Actions workflow. <br>For example:</li></ol><pre>name: Playwright Tests <br>on:<br>  push:<br>    branches: [ master ]<br>  pull_request:<br>    branches: [ master ]<br>jobs:<br>  test:<br>    timeout-minutes: 60<br>    runs-on: ubuntu-latest    <br>    steps:<br>    - uses: actions/checkout@v3<br>    - uses: actions/setup-node@v3<br>      with:<br>        node-version: 16<br>    - name: Install browsers<br>      run: ./batect playwright-install    <br>    - name: Install dependencies<br>      run: ./batect install<br>    - name: Run Playwright tests<br>      run: ./batect test<br>    - uses: actions/upload-artifact@v3<br>      if: always()<br>      with:<br>        name: playwright-report<br>        path: playwright-report/<br>        retention-days: 30</pre><p>2. Commit and push this file to your repository. This will trigger the CI workflow and run your tests using Batect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDSRizVKMqHhEnlzwLRglg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXy74vcyIHO-JUeVdz-M7w.png" /></figure><h4>Conclusion</h4><p>Batect is a highly effective tool for defining and managing development tasks and containers. Its various features make it a useful tool for complex projects that require a streamlined and efficient deployment process.</p><p>However, it is important to carefully consider whether Batect is the right choice for your project before opting it for your project.</p><p>If you want to learn more about Batect, then follow this <a href="https://batect.dev/docs/"><strong>link</strong></a>.</p><p>For more information, you can refer to my GitHub project for the same.</p><p>Github link : <a href="https://github.com/ISanjeevKumar/playwright-batect">https://github.com/ISanjeevKumar/playwright-batect</a></p><blockquote><strong>[Update]<em> Batect is no longer maintained, so please avoid using it. I will soon write a blog about an alternative: Taskfile.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94670e9edb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying the Single Responsibility Principle in Automation Test Code]]></title>
            <link>https://medium.com/@iamsanjeevkumar/applying-the-single-responsibility-principle-in-automation-test-code-7a08d9e2fb5f?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a08d9e2fb5f</guid>
            <category><![CDATA[rp]]></category>
            <category><![CDATA[test-automation-framework]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Fri, 16 Dec 2022 09:28:58 GMT</pubDate>
            <atom:updated>2022-12-16T09:45:49.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiVTJ3WCu9ruD5q1aJ_fBQ.png" /></figure><p>In software development, SOLID design principles are crucial for writing understandable, flexible, and maintainable software.The development of automation frameworks is now also considered as software development, so following SOLID principles in test automation is also very important.</p><p>First, let’s understand SOLID principles on very high level.</p><h3>About SOLID principles</h3><p>SOLID is an acronym that represents five design principles. These principles are:</p><ol><li><strong>Single Responsibility Principle</strong></li><li><strong>Open-Closed Principle</strong></li><li><strong>Liskov Substitution Principle</strong></li><li><strong>Interface Segregation Principle</strong></li><li><strong>Dependency Inversion Principle</strong></li></ol><p>Let’s deep dive into <strong>Single Responsibility Principle </strong>and understand how we can apply the same in test automation.</p><h4><strong>Single Responsibility Principle</strong></h4><blockquote>This principle states that “ Every software module should have only one reason to change”.</blockquote><p>It means that a class or module should have only one reason to change. In other words, a class or module should have a single, well-defined responsibility or purpose.</p><p>In the context of automation testing, applying the SRP can help to ensure that your test code is maintainable, flexible, and easy to understand. Here are a few ways you might apply the SRP when designing your automation testing strategy:</p><ol><li>Separate test action and validation methods : Rather than cluttering your test action with validation code, consider creating separate methods. This will make your test code easier to read and understand, and will also make it easier to reuse these methods in other tests.</li><li>Encapsulate test data: Instead of hardcoding test data directly in your test logic, consider encapsulating it in separate data objects or files. This will make your test logic easier to read and understand, and will also make it easier to update and maintain your test data.</li><li>Create modular test logic: Rather than creating monolithic test methods that do everything in one place, consider breaking your test logic into smaller, more modular methods that each have a single responsibility. This will make your test code easier to understand and maintain, and will also make it easier to reuse your test logic in other tests.</li></ol><p>Let’s understand this with a code example.</p><p>Here is an example of a Page Object class that violates the Single Responsibility Principle in test automation:</p><pre>class LoginPage {<br><br>protected get username() {<br>    return $(&#39;input[id=&quot;user-name&quot;]&#39;);<br>  }<br><br>  protected get password() {<br>    return $(&#39;input[id=&quot;password&quot;]&#39;);<br>  }<br><br>  protected get submitBtn() {<br>    return $(&#39;input[id=&quot;login-button&quot;]&#39;);<br>  }<br><br>  public async setUsername(username: string): {<br>    await this.username.setValue(username);<br>  }<br><br>  public async setPassword(password: string): {<br>       await this.password.setValue(password);<br>  }<br><br>  public async submitForm():{<br>    await this.submitBtn.click();<br>  }<br><br>  public async login(data: any):{<br>    // Violating the Single Responsibility Principle by handling navigation <br>   // and test data setup in the Page Object class<br>    const { username, password } = JSON.parse(data);<br>    await browser.url(https://medium.com/&#39;http://facebook.com/login&#39;);<br>    await this.setUsername(username);<br>    await this.setPassword(password);<br>    await this.submitForm();<br>  }<br>}</pre><p>In this example, the LoginPage class has multiple responsibilities: representing the login page and exposing methods for interacting with it, as well as handling navigation to the login page and deserializing data. This violates the Single Responsibility Principle, as the class now has multiple reasons to change. For example, if the URL of the login page changes, the login method would need to be updated to reflect the new URL. Similarly, if the structure of the data changes, the login method would need to be updated to structure the new data format.</p><p>By handling data deserialization in the Login page class, we have created a class that is more difficult to understand and maintain, and that is less reusable in other tests because of tight coupling with deserialization logic and navigation .</p><p>In order to follow the Single Responsibility Principle, we should separate these responsibilities into separate classes or methods.</p><p><strong>Optimised solution</strong></p><pre>class LoginPage {<br> protected get username() {<br>    return $(&#39;input[id=&quot;user-name&quot;]&#39;);<br>  }<br><br>  protected get password() {<br>    return $(&#39;input[id=&quot;password&quot;]&#39;);<br>  }<br><br>  protected get submitBtn() {<br>    return $(&#39;input[id=&quot;login-button&quot;]&#39;);<br>  }<br><br>  public async setUsername(username: string): {<br>    await this.username.setValue(username);<br>  }<br><br>  public async setPassword(password: string): {<br>       await this.password.setValue(password);<br>  }<br><br>  public async submitForm():{<br>    await this.submitBtn.click();<br>  }<br>  <br>  public async load():{<br>       await browser.url(https://medium.com/&quot;/&quot;);<br>  }<br>}<br><br>// Test spec example<br>describe(&quot;Login Test&quot;, function () {<br>  it(&quot;should be able to login with valid credentials&quot;, async function () {<br>    const app = new App();<br>// Separating data deserialization and test setup from the Page Object class<br>    const { username, password } = JSON.parse(data);<br>    await app.LoginPage.load(&#39;http://facebook.com/login&#39;);<br>    await app.loginPage.setUsername(username);<br>    await app.loginPage.setPassword(password);<br>    await app.loginPage.submitForm();<br>  });<br><br>});</pre><p>In this optimized version of the code, we have separated the responsibilities of the Page Object class and the test logic into separate classes. The LoginPage class now has a single responsibility: representing the login page and exposing methods for interacting with it. The LoginTest class is responsible for handling data deserialization , as well as interacting with the LoginPage object to perform the login.</p><h4>Conclusion</h4><p>It is important to carefully consider the responsibilities of your Page Object classes and ensure that they are focused and well-defined, in order to follow the Single Responsibility Principle and create maintainable, flexible, and easy-to-understand test code.</p><p>Thanks for Reading!!!</p><p>The next principles will be discussed in my next blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a08d9e2fb5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Models For Maintainable Data-Driven Automation Tests]]></title>
            <link>https://medium.com/@iamsanjeevkumar/data-models-for-maintainable-data-driven-automation-tests-cdd8f71f2ab0?source=rss-ba3b361a5843------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd8f71f2ab0</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[data-driven]]></category>
            <dc:creator><![CDATA[Sanjeev Kumar]]></dc:creator>
            <pubDate>Wed, 14 Dec 2022 09:29:59 GMT</pubDate>
            <atom:updated>2022-12-14T09:58:38.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaA5Lm4A7VLNk28S0vzWtA.png" /></figure><p>The basic idea behind data-driven testing is to separate test logic from the test data. When you have test steps that are the same, but the test data needs to be different, this approach works best. For data driven test , you can use any file extensions to save your test data , but many of us use JSON files because they are lightweight and easy to use.</p><p>So, I will use the JSON file to demonstrate the use of the data model for data driven tests.</p><p>To create data-driven tests using a JSON file, you would first need to create a JSON file that contains the test data. Here is an example of a JSON file with test data:</p><pre>{<br>  &quot;testCases&quot;: [<br>    {<br>      &quot;name&quot;: &quot;userShouldbeLogin&quot;,<br>      &quot;username&quot;: &quot;validUser&quot;,<br>      &quot;password&quot;: &quot;validPassword&quot;<br>    },<br>    {<br>      &quot;name&quot;: &quot;userShouldNotbeLogin&quot;,<br>      &quot;username&quot;: &quot;invalidUser&quot;,<br>      &quot;password&quot;: &quot;invalidPassword&quot;<br>    },<br>  ]<br>}</pre><p>Then, you would need to write a logic that reads the JSON file and uses the test data to run the tests. Here is an example of how that test might look:</p><pre>import * as userdata from &quot;../data/test-data.json&quot;;<br><br>   // Loop through each test case in the JSON file<br>for (const testCase of userdata.testCases) {<br><br> test(testCase.name , async ({page, login}) =&gt; {<br>    await login.navigateToLoginPage();<br>  // Inside the login function , Valid and invalid cases are handled<br>    await login.login(testCase.username,testCase.password);<br>  });<br>}</pre><p>This is a very simple example of how data driven tests can be implemented using json files. You may face some challenges with this approach, such as difficulty in traversing nested objects in the test script if you need to work with complex nested objects.</p><p>Another potential challenge with this approach is that JSON data can be difficult to maintain, especially if the data is being used across multiple tests or test suites.</p><p>For instance, changes to the field names or structure of the JSON data will also require updates to the test automation scripts. This can be time-consuming and error-prone, since errors in the scripts may not be detected until the tests are run.</p><p>So, Let’s see how we can address these challenges with the data model objects.</p><p>To create a data model for the aforementioned JSON data, We need to create classes to represent the data of json file. For instance, we will create a TestCase class with fields for the name, username, and password, and then create a TestCases class with a field for an array of TestCase objects.</p><p>Here is an example of how this data model could be implemented:</p><pre>class TestCase {<br>    name: string;<br>    username: string;<br>    password: string;<br><br>    constructor(name: string, username: string, password: string) {<br>        this.name = name;<br>        this.username = username;<br>        this.password = password;<br>    }<br>}<br><br>class TestCases {<br>    testCases: TestCase[];<br><br>    constructor(testCases: TestCase[]) {<br>        this.testCases = testCases;<br>    }<br>}</pre><p>To use this data model, now we need to deserialize the JSON data into a TestCases object and then access the individual test cases and their fields as needed in the test automation scripts.</p><pre>import * as userdata from &quot;../data/test-data.json&quot;;<br>import { TestCase, TestCases } from &quot;./test-models&quot;;<br><br>const testCasesData = JSON.parse(userdata) as TestCases;<br><br>// Loop through each test case in the JSON file<br>for (const testCase of testCasesData.testCases) {<br>    test(testCase.name, async ({page, login}) =&gt; {<br>        await login.navigateToLoginPage();<br>        // Inside the login function, valid and invalid cases are handled<br>        await login.login(testCase.username, testCase.password);<br>    });<br>}</pre><p>In this example, the JSON data is imported from the test-data.json file and then parsed into a TestCases object. Then, a loop is used to iterate through the individual test cases.</p><p>If the username field in the JSON data is renamed to userName, the testCase.username reference in the test automation script will result in an error as the username field no longer exists. This error will be highlighted by the code editor or compiler, and it will be easy to identify the areas of the script that need to be updated.</p><p>To put it simply, using a data model for representing JSON data will proactively help in detecting and addressing changes to the JSON data structure and can make test automation scripts more maintainable and less error-prone.</p><p>Also, it becomes easier to traverse and access the individual fields in the JSON data. This is because the data model provides a structured and organised way to access the data, and the fields in the JSON data are mapped to properties in the data model.</p><p>This can help to reduce the complexity of the scripts and make it easier to understand and update the code.</p><h4>Disadvantage of Data Model</h4><p>I can think of one disadvantage from my experience.</p><p>Defining and implementing a data model requires additional effort and can be especially challenging when the test data is large and complicated.</p><p>Fortunately, there are various libraries available now that can dynamically generate data model classes for you and deserialize/serialize JSON data as well, so it shouldn’t be a major disadvantage.</p><p>For C#, Visual Studio has an inbuilt feature that allows you to create data models just by pasting complex JSON structures into it.</p><p>Note — If the structure of the JSON data changes, you will need to update the test automation scripts to reflect those changes. However, as mentioned earlier that using a data model to represent the JSON data can make it easier to update the test scripts, and it can help to reduce the risk of errors. Hence , I am not considering it as a major disadvantage.</p><h4>Conclusion</h4><p>It is generally considered good practice to use data models in test automation. This approach helps to make the tests more maintainable and easier to understand.</p><p>In my opinion, whether or not to use data models in test automation is ultimately a decision that should be based on the specific needs and constraints of your testing environment. If you are dealing with large and complex sets of test data, and if maintainability and reliability are important considerations, then using data models might be a good approach. On the other hand, if you are dealing with relatively simple and straightforward test data, and if flexibility is a key requirement, then using data models might not be necessary.</p><p>Overall, while using data models in test automation can have many benefits, it is important to carefully consider the potential disadvantages and weigh them against the benefits in the context of your specific testing needs before opting for test automation.</p><p>Thanks for Reading !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd8f71f2ab0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>