<?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 Ankita Bhattacharjee on Medium]]></title>
        <description><![CDATA[Stories by Ankita Bhattacharjee on Medium]]></description>
        <link>https://medium.com/@anks2906?source=rss-35994b380e4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*89npARE92K43h8Z4</url>
            <title>Stories by Ankita Bhattacharjee on Medium</title>
            <link>https://medium.com/@anks2906?source=rss-35994b380e4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:12:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anks2906/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[Taming Telescoping Overloads: A Fluent Request Builder Pattern for Rest Assured]]></title>
            <link>https://medium.com/@anks2906/taming-telescoping-overloads-a-fluent-request-builder-pattern-for-rest-assured-96e07334e9cb?source=rss-35994b380e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e07334e9cb</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[restassured]]></category>
            <category><![CDATA[sdet]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ankita Bhattacharjee]]></dc:creator>
            <pubDate>Tue, 27 Oct 2026 11:32:19 GMT</pubDate>
            <atom:updated>2026-10-27T12:11:44.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBVNhx7d2G4drSwvTK8ThQ.png" /></figure><p><em>My API test client needed a new overload for almost every kind of request. I replaced them all with one small fluent builder. Here’s how I did it, and why I didn’t just call Rest Assured directly.</em></p><p>If you’ve ever looked at a line like send(method, path, null, null, pathParams, false) and tried to guess which null is which, you know the feeling.</p><p>That was my API client layer for sometime. I maintain a Cucumber BDD framework that tests the Conduit (RealWorld) app at three levels: the REST API with Rest Assured, the web UI with Selenium, and the Postgres database underneath.</p><p>Every API call in the framework goes through one class, HttpRestClient. That’s on purpose. It’s where auth gets attached, where passwords are kept out of the logs, and where each request and response is saved, so a failed scenario can attach the full HTTP exchange to the report.</p><p>It worked fine. Until the class had to do one more thing.</p><h3>The problem: an overload for every combination</h3><p>Here’s what the client’s public API looked like before the refactor:</p><pre>public Response sendHttpRequest(Method method, String path) {<br>    return send(method, path, null, null, null, false);<br>}<br><br>public Response sendHttpRequest(Method method, String path, Object body) {<br>    return send(method, path, body, null, null, false);<br>}<br><br>public Response sendHttpRequestWithQueryParams(Method method, String path, Map&lt;String, ?&gt; queryParams) {<br>    return send(method, path, null, queryParams, null, false);<br>}<br><br>public Response sendHttpRequestWithPathParams(Method method, String path, Map&lt;String, ?&gt; pathParams) {<br>    return send(method, path, null, null, pathParams, false);<br>}<br><br>/** Same as sendHttpRequest but bodies (e.g. credentials, tokens) are not logged. */<br>public Response sendSensitiveHttpRequest(Method method, String path, Object body) {<br>    return send(method, path, body, null, null, true);<br>}</pre><p>Five public methods, all calling one private send with six parameters in a row. The call sites weren’t much better:</p><pre>httpRestClient.sendHttpRequestWithPathParams(Method.DELETE, ARTICLES_SLUG, Map.of(&quot;slug&quot;, slug));<br>httpRestClient.sendSensitiveHttpRequest(Method.POST, LOGIN, Map.of(&quot;user&quot;, user));</pre><p>Then the questions started. What about a request that needs a path parameter <em>and</em> a query parameter? A custom header? A sensitive call with query parameters? Multipart uploads?</p><p>Each answer meant another overload. And the combinations grow much faster than the features do.</p><p>This has a name: the <strong>telescoping method</strong> anti-pattern. The usual way out is a builder.</p><h3>The obvious question: why not call Rest Assured directly?</h3><p>It’s the first thing any reviewer asks, and it’s a fair one. Rest Assured already has a fluent API: given().queryParam(…).body(…).when().post(…). Why wrap it in another one?</p><p>Because every request in this framework has to do four things, every single time:</p><p>1. <strong>Start from a fresh request on an immutable base spec.</strong> An earlier version merged specs between calls, and the merged spec quietly reset the base URI and body. Building each request from a fresh given().spec(baseSpec) closes that leak.</p><p>2. <strong>Attach logging filters that respect sensitive data.</strong> Login and registration bodies carry passwords, so those calls log only the URI and status, never the body.</p><p>3. <strong>Add the right Authorization header.</strong> Conduit uses Token &lt;jwt&gt;, not Bearer. And some negative tests need to send a deliberately broken header instead.</p><p>4. <strong>Save the response and the exchange log in the scenario context,</strong> so assertion steps can read them and failure hooks can attach them to the report.</p><p>If step definitions called given() themselves, each of these rules would become a habit. And sooner or later, someone forgets a habit.</p><p>So the goal was simple: keep the one entry point, lose the overloads.</p><h3>The fix: the builder collects, the client sends</h3><p>The main idea is a strict split of jobs.</p><p>A new class, ApiRequest, only collects data: method, path, body, query params, path params, extra headers and a sensitive flag. It never touches Rest Assured. When you call send(), it hands itself back to the client, and the client builds the real request the same way it always did.</p><pre>/**<br> * One API call, described fluently. Created only by HttpRestClient.request(...);<br> * nothing is sent until send(). Single-use: build it, send it, don&#39;t store it.<br> */<br>@Getter(AccessLevel.PACKAGE)<br>public class ApiRequest {<br><br>    private final HttpRestClient httpRestClient;<br>    private final Method method;<br>    private final String path;<br>    private final Map&lt;String, Object&gt; queryParams = new LinkedHashMap&lt;&gt;();<br>    private final Map&lt;String, Object&gt; pathParams = new LinkedHashMap&lt;&gt;();<br>    private final Map&lt;String, String&gt; extraHeaders = new LinkedHashMap&lt;&gt;();<br>    private Object body;<br>    private boolean sensitive;<br><br>    ApiRequest(HttpRestClient httpRestClient, Method method, String path) {<br>        this.httpRestClient = httpRestClient;<br>        this.method = method;<br>        this.path = path;<br>    }<br><br>    public ApiRequest body(Object body) {<br>        this.body = body;<br>        return this;<br>    }<br><br>    public ApiRequest queryParam(String name, Object value) {<br>        queryParams.put(name, requireValue(name, value));<br>        return this;<br>    }<br><br>    public ApiRequest pathParam(String name, Object value) {<br>        pathParams.put(name, requireValue(name, value));<br>        return this;<br>    }<br><br>    public ApiRequest header(String name, String value) {<br>        extraHeaders.put(name, value);<br>        return this;<br>    }<br><br>    /** Request and response bodies are kept out of logs and reports. */<br>    public ApiRequest sensitive() {<br>        sensitive = true;<br>        return this;<br>    }<br><br>    public Response send() {<br>        return httpRestClient.send(this);<br>    }<br><br>    private static Object requireValue(String name, Object value) {<br>        if (value == null) {<br>            throw new FrameworkException(&quot;Request parameter &#39;&quot; + name + &quot;&#39; is null&quot;);<br>        }<br>        return value;<br>    }<br>}</pre><p>A few small details matter more than they look:</p><p>• <strong>The constructor is package-private.</strong> The only way to get an ApiRequest is httpRestClient.request(…), so a request can’t exist without the client that owns auth and logging. That makes request() a small <strong>factory method</strong>.</p><p>• <strong>send(ApiRequest) on the client is package-private too.</strong> Step definitions and API classes can’t skip the builder.</p><p>• <strong>The maps are LinkedHashMaps.</strong> Parameters show up in the logs in the order you added them, which makes two runs easier to compare.</p><p>• <strong>Null values fail fast.</strong> Otherwise queryParam(“author”, null) would make Rest Assured send a parameter with no value. That’s a silent bug that shows up as a confusing 4xx a few steps later.</p><p>On the client side, the public API shrinks to one method. The old send keeps its body but takes the request object instead of six parameters:</p><pre>public ApiRequest request(Method method, String path) {<br>    return new ApiRequest(this, method, path);<br>}<br><br>Response send(ApiRequest apiRequest) {<br>    LogHelper.logSendHttpRequest(apiRequest.getMethod(), getConfigurations().getApiBaseUri() + apiRequest.getPath());<br><br>    ByteArrayOutputStream exchangeLog = new ByteArrayOutputStream();<br>    PrintStream logStream = new PrintStream(exchangeLog, true);<br>    boolean sensitive = apiRequest.isSensitive();<br><br>    RequestSpecification request = RestAssured.given()<br>            .spec(baseSpec)<br>            .filter(new RequestLoggingFilter(sensitive ? LogDetail.URI : LogDetail.ALL, true, logStream, true))<br>            .filter(new ResponseLoggingFilter(sensitive ? LogDetail.STATUS : LogDetail.ALL, true, logStream));<br><br>    if (apiRequest.getBody() != null) {<br>        request.body(apiRequest.getBody());<br>    }<br>    if (!apiRequest.getQueryParams().isEmpty()) {<br>        request.queryParams(apiRequest.getQueryParams());<br>    }<br>    if (!apiRequest.getPathParams().isEmpty()) {<br>        request.pathParams(apiRequest.getPathParams());<br>    }<br>    if (!apiRequest.getExtraHeaders().isEmpty()) {<br>        request.headers(apiRequest.getExtraHeaders());<br>    }<br>    if (!setsOwnAuthorization(apiRequest)) {<br>        applyClientAuth(request);<br>    }<br><br>    Response response = request.request(apiRequest.getMethod(), apiRequest.getPath());<br>    commonContext.storeResponse(response);<br>    commonContext.recordExchange(exchangeLog.toString());<br>    return response;<br>}</pre><h3>The result: calls that read like sentences</h3><p>Each call now says only what it needs:</p><pre>httpRestClient.request(Method.DELETE, ARTICLES_SLUG).pathParam(&quot;slug&quot;, slug).send();<br><br>httpRestClient.request(Method.GET, ARTICLES).queryParam(&quot;author&quot;, user.getUsername()).send();<br><br>httpRestClient.request(Method.POST, LOGIN).sensitive().body(Map.of(&quot;user&quot;, user)).send();</pre><p>Compare that last line with the old sendSensitiveHttpRequest(Method.POST, LOGIN, Map.of(“user”, user)). Before, “sensitive” was baked into a method name. Now it’s just one more thing you can add to any request.</p><h3>Not quite a textbook builder</h3><p>If you’ve read about the builder pattern before, you might notice this one ends a little differently.</p><p>A classic builder ends in build(), which returns a finished, usually immutable object. Mine ends in send(), which runs the request straight away.</p><p>That makes it a <strong>builder with a terminal operation</strong>. It’s the same style as Rest Assured’s own given()…when().get(), or Java Streams’ .filter().map().collect(). You describe the work step by step, and the last call actually does it.</p><h3>The trade-offs</h3><p>No pattern is free. Here’s what this one costs:</p><p>• <strong>A forgotten send() after request(…) compiles and does nothing.</strong> Worse, the next assertion step reads the previous response from the scenario context and fails with a confusing message. Error Prone’s @CheckReturnValue can catch it. Otherwise, it’s down to code review.</p><p>• <strong>The builder is mutable and single-use.</strong> That’s fine when you build and send a request in one line, but don’t store ApiRequest objects in fields or contexts.</p><p>• <strong>It’s one more layer.</strong> New people on the team have to learn request(…).send() on top of Rest Assured. In return, the four rules above are enforced instead of remembered.</p><h3>What it bought me</h3><p>The real test of a design like this is the next feature.</p><p>Before, adding multipart upload would have meant new overloads for every combination it could show up in. Now it’s one field and one method on ApiRequest, plus one if in send(). Nothing else changes, and no existing call site gets touched.</p><h3>What I’d tell anyone trying this</h3><p>• <strong>Keep one choke point.</strong> Rules that live in one class get enforced. Rules that live in people’s heads get forgotten.</p><p>• <strong>Let the builder collect and the client execute.</strong> Keeping Rest Assured out of the builder means auth, logging and the base spec stay in one place.</p><p>• <strong>Fail fast on bad input.</strong> A null parameter that blows up straight away is much easier to debug than a confusing 4xx a few steps later.</p><p>Next, I want to make authentication explicit, instead of the client quietly storing a token as a side effect of logging in. That one deserves its own article.</p><p><em>The full framework is on GitHub: [</em><a href="https://github.com/bbankita/demo-automation-framework">https://github.com/bbankita/demo-automation-framework</a><em>]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e07334e9cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beating the 20-Minute Wait: An Async Top-Up Pattern for Slow External Test Dependencies]]></title>
            <link>https://medium.com/@anks2906/beating-the-20-minute-wait-an-async-top-up-pattern-for-slow-external-test-dependencies-b48a83ef66a6?source=rss-35994b380e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b48a83ef66a6</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Ankita Bhattacharjee]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 11:57:38 GMT</pubDate>
            <atom:updated>2026-10-08T11:57:38.656Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to stop your test suite from blocking on things it doesn’t control.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBjg3Fv_PmMIJ_RnJT7rUg.png" /></figure><h3>The problem</h3><p>If you’ve worked on test automation long enough, you’ve probably hit this wall. Some of the things your tests need don’t come from a system you own. You ask for a “device,” a “sandbox account,” a “provisioned VM,” a “verified identity” (every domain has its own word for it). Then some separate backend process has to move that request from “requested” to “usable” before a test can touch it.</p><p>And that doesn’t happen fast. For us, it was an external job that took 15 to 25 minutes. No webhook. No completion event. Just poll and wait.</p><p>Now picture dozens of parallel test threads, all wanting a fresh resource the moment they start. You end up choosing between three bad options:</p><p>• Wait synchronously, and watch a 90-second run turn into a 25-minute one.</p><p>• Over-provision ahead of time and hope enough gets promoted before the tests need it. Sometimes it works. Sometimes it doesn’t.</p><p>• Mock the dependency, which feels like progress until you realize you’ve quietly stopped testing the real integration.</p><p>We didn’t like any of them. What we wanted was easy to say and harder to build: tests grab already-ready resources instantly, and the pool refills itself in the background while nobody waits.</p><h3>How we got here</h3><p>This wasn’t the first design. The first one was the obvious one: a separate class with a @BeforeSuite method that seeded fresh devices for each requester ID before the suite started, so every test had data waiting for it.</p><p>It worked occasionally. Most of the time it didn’t. The seeding query itself was fine (we checked). The problem was downstream. When we pushed several batches through one after another, the external job that generates activation codes failed far more often than it succeeded. And even when it worked, the tests were depending on data that wouldn’t be usable for another 15 to 25 minutes.</p><p>So we wrote down what we actually needed before touching the code again:</p><p>1. <strong>Stop firing batches back to back.</strong> Whatever we sent the external system had to be small and spaced out.</p><p>2. <strong>Tests must never depend on seeding succeeding.</strong> A test should only ever get a device that’s already fully usable.</p><p>3. <strong>No manual test-data maintenance.</strong> When a requester ID’s devices run out, the framework should notice and refill on its own.</p><p>4. <strong>No added pre- or post-processing time.</strong> The suite shouldn’t get slower because of any of this.</p><p>5. <strong>We were happy to keep a buffer.</strong> An initial stock of devices per requester ID was fine, as long as the framework maintained it.</p><p>Everything below is an answer to one of those five lines.</p><h3>The pattern: an async-refilled resource pool</h3><p>Here’s the shape of it. Think of a small state machine sitting between your tests and the slow external system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfO8b3IHFekWG9q3n5hT0Q.png" /></figure><p>The whole trick is in one idea: <strong>the test that notices the pool is low is never the test that waits for the refill.</strong> It kicks off the refill and gets on with whatever’s already there. The refill pays off for some future run, not the one that asked for it. Once that clicked for us, the rest of the design mostly fell into place.</p><h3>1. The read path</h3><p>We keep a local database that mirrors whatever the external system has already promoted. Tests ask that database, not the external system:</p><pre>public static List&lt;Resource&gt; getAvailableResources(String batchKey, int count) {<br>    // pull already-promoted, not-yet-consumed rows for this batch key<br>    List&lt;Resource&gt; resources = queryLocalRegistry(batchKey, count);<br><br>    // cheap in-memory check; any DB work for the top-up happens off this thread<br>    triggerAsyncTopUpCheck(batchKey);<br><br>    if (resources.size() &lt; count) {<br>        throw new SkipException(&quot;Only &quot; + resources.size() + &quot;/&quot; + count<br>                + &quot; ready resources for &quot; + batchKey + &quot;; pool is refilling, retry later&quot;);<br>    }<br>    return resources;<br>}</pre><p>If there aren’t enough, the test skips with a clear reason instead of hanging. And that matters more than it sounds. “Come back in 20 minutes” is something a person can act on. A test that just sits there forever isn’t.</p><p>Notice what the calling thread <em>doesn’t</em> do. It doesn’t count rows. It doesn’t decide whether the pool is low. That call happens on the background thread, so the test’s critical path never pays for it.</p><p>If there aren’t enough, the test skips with a clear reason instead of hanging. And that matters more than it sounds. “Come back in 20 minutes” is something a person can act on. A test that just sits there forever isn’t.</p><p>Notice what the calling thread <em>doesn’t</em> do. It doesn’t count rows. It doesn’t decide whether the pool is low. That call happens on the background thread, so the test’s critical path never pays for it.</p><h3>2. The async top-up, done carefully</h3><p>The obvious version is “just spawn a thread and insert a batch.” It works right up until real concurrency shows up, and then it breaks in two ways. Lots of parallel test threads all decide, at the same moment, to top up the same batch key. That’s redundant writes and wasted quota on a system you don’t control. And the burst of writes starts fighting the read path for database connections. Both problems turned out to be cheap to fix.</p><pre>private static final int  LOW_WATER_MARK        = 1000;<br>private static final int  TOPUP_BATCH_SIZE      = 30;<br>private static final long TOPUP_COOLDOWN_MILLIS = TimeUnit.MINUTES.toMillis(20);<br><br>private static final ExecutorService TOPUP_EXECUTOR =<br>        Executors.newSingleThreadExecutor(daemonThreadFactory(&quot;pool-topup&quot;));<br><br>private static final ConcurrentHashMap&lt;String, Long&gt; lastTopUpTriggeredAt = new ConcurrentHashMap&lt;&gt;();<br><br>private static void triggerAsyncTopUpCheck(String batchKey) {<br>    long now = System.currentTimeMillis();<br>    Long last = lastTopUpTriggeredAt.get(batchKey);<br><br>    if (last == null) {<br>        if (lastTopUpTriggeredAt.putIfAbsent(batchKey, now) != null) {<br>            return; // another thread claimed the first window<br>        }<br>    } else {<br>        if (now - last &lt; TOPUP_COOLDOWN_MILLIS) {<br>            return; // still cooling down, in-memory check only<br>        }<br>        if (!lastTopUpTriggeredAt.replace(batchKey, last, now)) {<br>            return; // another thread claimed this expired window first<br>        }<br>    }<br><br>    TOPUP_EXECUTOR.submit(() -&gt; {<br>        long start = System.currentTimeMillis();<br>        try {<br>            long available = countAvailable(batchKey);<br>            if (available &lt; LOW_WATER_MARK) {<br>                seedFreshBatch(TOPUP_BATCH_SIZE, batchKey);<br>                log.info(&quot;Topped up {} resources for {} ({} were available) in {} ms&quot;,<br>                        TOPUP_BATCH_SIZE, batchKey, available, System.currentTimeMillis() - start);<br>            } else {<br>                log.debug(&quot;Pool for {} healthy ({} available), no top-up needed&quot;, batchKey, available);<br>            }<br>        } catch (Exception e) {<br>            log.error(&quot;Background top-up failed for {}&quot;, batchKey, e);<br>        }<br>    });<br>}</pre><p>Here’s what each piece is doing:</p><p>• <strong>One thread does all the top-up work.</strong> A single-threaded executor means no thundering herd on the connection pool and no half-batches interleaving with each other.</p><p>• <strong>The “is the pool low?” question gets asked on that thread, not the caller’s.</strong> Counting rows is a database query, so it happens in the background. The test thread only touches an in-memory map.</p><p>• <strong>A 20-minute cooldown per key.</strong> We roughly matched it to how often the external job promotes things. The first thread to notice a shortage triggers one check. The next fifty threads that notice the same shortage? They do nothing.</p><p>• <strong>Small, steady batches.</strong> 30 at a time, whenever we drop under 1,000 available. It keeps the pool topped up gradually instead of dumping one giant burst on the external system.</p><p>• <strong>Failures wait their turn.</strong> If a top-up throws, the cooldown window stays claimed, so nothing retries for 20 minutes. We were fine with that, because it’s gentle on a system we don’t own. If you’d rather retry sooner, release the claim in the catch with lastTopUpTriggeredAt.remove(batchKey, now).</p><h4>The subtle bug: putIfAbsent alone is not a cooldown</h4><p>This is the part I most want you to take away, because it looks completely fine. Our first cooldown was this:</p><p>Long last = lastTopUpTriggeredAt.get(batchKey);<br> if (last != null &amp;&amp; now — last &lt; cooldownMillis) return;<br> if (lastTopUpTriggeredAt.putIfAbsent(batchKey, now) != null) return;</p><p>Read it once and it seems right. It passes every short test run, too. But putIfAbsent only writes when the key is <em>missing</em>, and nothing ever removes the key. So after the first top-up for a batch key, every later call finds the old timestamp still sitting in the map. The cooldown check passes (the window really has expired), then putIfAbsent hands back that stale value, and the method bails out. <strong>Each batch key got exactly one top-up for the lifetime of the JVM.</strong></p><p>In a 90-second suite, you’d never notice. In a long-running one, the pool slowly drains and just… stops refilling. No error. No log line. Nothing.</p><p>The fix is to treat the two cases differently, and make each one atomic:</p><p>• <strong>No entry yet:</strong> putIfAbsent(key, now). One thread wins.</p><p>• <strong>An expired entry:</strong> replace(key, last, now). This only succeeds if the value is still the exact timestamp this thread read. So exactly one thread claims each expired window.</p><p>The bigger lesson is one I keep relearning: a check-then-act on a concurrent map is only safe if the <em>act</em> depends on what you checked.</p><h4>Shutting down without losing a batch</h4><p>The executor’s thread is a daemon, so it never keeps the JVM alive on its own. Good. But that also means the JVM can kill it mid-write on a perfectly normal exit, with no chance to finish the seed transaction or even log anything. So we added a shutdown hook that gives it a bounded grace period to drain:</p><pre>private static final int TOPUP_SHUTDOWN_GRACE_PERIOD_SECONDS = 180;<br><br>static {<br>    Runtime.getRuntime().addShutdownHook(new Thread(() -&gt; {<br>        TOPUP_EXECUTOR.shutdown();<br>        try {<br>            if (!TOPUP_EXECUTOR.awaitTermination(TOPUP_SHUTDOWN_GRACE_PERIOD_SECONDS, TimeUnit.SECONDS)) {<br>                log.warn(&quot;Top-up did not finish within the {}s grace period; forcing stop, &quot;<br>                        + &quot;top-up may not have completed.&quot;, TOPUP_SHUTDOWN_GRACE_PERIOD_SECONDS);<br>                TOPUP_EXECUTOR.shutdownNow();<br>            }<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>            TOPUP_EXECUTOR.shutdownNow();<br>        }<br>    }, &quot;pool-topup-shutdown&quot;));<br>}</pre><p>Why 180 seconds? It’s not a number we pulled out of the air. A full seed batch fires roughly 150 sequential inserts (there’s no JDBC batching in this codebase), and it has to live alongside the framework’s 60-second per-query timeout. We sized the grace period so a batch that’s already in flight can realistically finish.</p><p>I want to be upfront about the limit, though. This only helps on a normal exit. A kill -9 or an OOM kill skips shutdown hooks completely and can leave a half-committed batch behind. We decided to live with that. It’s rare, and it heals itself, because the seeding transaction is wrapped so a partial write rolls back. Engineering around it wasn’t worth it.</p><h3>3. Cheap, batch-shared identifiers</h3><p>Here’s a small one that saved more time than you’d expect. When you seed N resources for a test run, you don’t need N fully independent random identifiers. Two cheaper habits did the job:</p><p>• <strong>Anything that describes the whole batch gets generated once.</strong> A catalog code, a purchase-order number: make one and reuse it on every row. It’s exactly how one order number covers every line item on a purchase order.</p><ul><li><strong>Anything that has to be unique per row comes from one random base.</strong> Instead of a fresh random draw every time, bump the base with a cheap increment-and-wrap:</li></ul><pre>// base + i, wrapping the last 3 digits at 1000 so a 900-device batch never overflows<br>private static String incrementTrailingDigits(String base, int i) {<br>    int tail = (Integer.parseInt(base.substring(base.length() - 3)) + i) % 1000;<br>    return base.substring(0, base.length() - 3) + String.format(&quot;%03d&quot;, tail);<br>}</pre><p>Simple, and collision-safe enough for a test environment. Just don’t use it for anything a customer ever sees.</p><h3>Why async, and not @AfterSuite or a scheduled job</h3><p>This is the question I’d ask if I were reviewing this, so let’s take it head on. There are two simpler-looking options, and for a different suite either one might be the right call.</p><p><strong>Option 1: top up in @AfterSuite.</strong> Tests finish, you count, you seed, done. No background thread, no cooldown map, no shutdown hook.</p><p><strong>Option 2: a scheduled job.</strong> Something in CI runs every 20 minutes, counts the pool and seeds if it’s low. The tests just read.</p><p><strong>Option 3: top up in </strong><strong>@AfterClass.</strong> When an inventory test class finishes, it checks the pool and seeds if it&#39;s low. No executor, no daemon thread, no shutdown hook, and it still fires partway through the run.</p><p>Here’s why neither fit our situation:</p><p>• <strong>The external job runs on a fixed 20-minute schedule.</strong> A seeded batch waits for the next run, so seeding earlier means getting promoted earlier. A top-up that fires at the first shortage mid-suite catches a promotion cycle <em>during</em> the run. A post-suite top-up always misses every cycle that happens while the suite is running. That schedule is also why the cooldown is 20 minutes. Seeding more often than the job runs gains nothing.</p><p>• <strong>The suite runs 60 to 100 minutes and drains the pool while it runs.</strong> Activation and deactivation scenarios for each requester ID keep pulling devices the whole time. A 60–100 minute run spans three to five promotion cycles, so a mid-run refill can actually serve tests later in the same run.</p><p>• <strong>Up to 30 threads hit the pool at once.</strong> All the inventory tests sit in one TestNG &lt;test&gt; running parallel=”methods” with 30 threads. When the pool dips, 30 threads can notice in the same second. That’s why the cooldown and the single-threaded executor exist: one refill instead of 30, and seeding writes that don’t fight 30 readers for connections.</p><p>• <strong>We’d ruled out pre- and post-processing time.</strong> A synchronous @AfterSuite seed of about 150 inserts adds real time to every Jenkins run. An <em>async</em> seed fired from @AfterSuite doesn’t work either, because the JVM exits right after it.</p><p>• <strong>We’d already tried a lifecycle hook.</strong> The @BeforeSuite version failed because batches went out back to back. Moving the seeding to the end of the suite doesn’t change that.</p><p>• <strong>A scheduled job keeps seeding when nobody’s testing.</strong> If the external promotion job is down, a scheduled top-up feeds it dead batches around the clock. Ours only seeds while tests are actually running and asking for devices.</p><p>• <strong>Seeding failures show up as test-config failures.</strong> A failed seed lands in the TestNG report as a configuration failure in. That’s noise for a problem that isn’t a test failure. In the executor, the same failure is just logged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9QBs6FeoslzdRq5OaZ190Q.png" /></figure><p>To be fair to the alternatives: if your suite runs for five minutes, or your pool never runs low mid-run, a module-scoped @AfterSuite, an @AfterClass or a CI post-build step is simpler and you should use it. The async version only earns its complexity when the run is long enough and busy enough for a mid-run refill to matter.</p><h3>When promotion fails after the inserts succeed</h3><p>Here’s the failure mode that worried me most. The seed goes in cleanly, every insert commits, and then 15 to 20 minutes later the external job fails to promote the batch. Those rows just sit there, never usable.</p><p>One decision made this far less scary than it sounds: <strong>the pool count only includes promoted rows.</strong> A failed batch never shows up as available, so the pool stays low, and the next cooldown window seeds again. The 20-minute cooldown ends up doing two jobs. It stops us re-seeding while a batch is probably still in flight, and it retries once that batch has probably failed. Across a 60–100 minute run, that’s several retry chances inside the same run, where a post-suite top-up would get one per run.</p><p>If we’d counted pending rows too, it would have been much worse. Dead rows would count as inventory forever, top-ups would stop, and tests would skip with no explanation.</p><p>But self-healing has limits, and they’re worth being honest about:</p><p>• <strong>A sustained outage looks exactly like “refilling.”</strong> If promotion keeps failing, tests keep skipping and batches keep going out, and nothing tells anyone. The fix is a stale-pending check at the start of each top-up. If more than a couple of batches’ worth of rows are still unpromoted after 40 minutes, log an error and stop seeding. That turns a silent slide into a loud “promotion is failing.”</p><p>• <strong>Refill speed is capped.</strong> At 30 devices per 20-minute window, a 100-minute run refills at most about 150 devices per requester ID. If a run uses more than that, the 1,000 buffer only delays the problem. Seeding in proportion to the shortfall (capped at a maximum batch size) recovers much faster.</p><p>• <strong>Tests that already skipped don’t come back.</strong> A refill only helps tests that start after it’s promoted.</p><p>• <strong>The cooldown is per JVM.</strong> If the suite ever runs on several CI agents at once, each has its own cooldown map. A check against the shared database (like the stale-pending one) covers that too.</p><h3>When this pattern is worth reaching for</h3><p>This isn’t something to build for every slow test. It earns its keep when all of these are true:</p><p>• A test dependency is provisioned by a system you don’t control and can’t speed up.</p><p>• That system is slow enough that waiting on it really hurts your suite’s runtime.</p><p>• Your tests are fine pulling from a shared pool instead of each getting a dedicated resource.</p><p>• “Not enough resources right now, try later” is an acceptable outcome, not a hard failure.</p><p>If the dependency is already fast, skip it. Same if every test truly needs its own freshly provisioned resource and nothing can be shared. You’d be adding moving parts for no real gain.</p><h3>TL;DR</h3><p>• Split the read path (grab ready resources from a local mirror) from the provisioning path (async, best-effort, off the critical path).</p><p>• Keep the calling thread’s work in memory. Ask “is the pool low?” on the background thread.</p><p>• Put a per-key cooldown on the trigger so parallel threads don’t stampede it, and claim each window atomically: putIfAbsent for the first one, replace(key, old, new) for expired ones. putIfAbsent on its own quietly turns your cooldown into a one-shot.</p><p>• Match the cooldown to the external system’s own schedule, and keep batches small and spaced out. Bursts were what broke the first design.</p><p>• Count only fully usable rows. Then a batch that fails promotion heals itself, and the cooldown doubles as your retry interval.</p><p>• Don’t let self-healing hide a real outage. Check for stale pending rows and stop seeding loudly.</p><p>• Run all writes through one single-threaded executor, and give it a shutdown grace period sized to a real batch. Accept that a hard kill can still leave a gap.</p><p>• Share identifiers that really describe the whole batch. Use cheap wraparound math for the ones that just need to be different.</p><p>• Only reach for async when the run is long and busy enough for a mid-run refill to matter. Otherwise, a post-suite top-up is simpler.</p><p>If your suite is stuck waiting on something slow today, start small. Stand up the local mirror and the skip-with-a-reason read path first. That alone changes how the suite feels. The async top-up can come next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b48a83ef66a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our Test Results Lived in Two Places. Here’s How We Fixed That.]]></title>
            <link>https://medium.com/@anks2906/our-test-results-lived-in-two-places-heres-how-we-fixed-that-ef56990ee62d?source=rss-35994b380e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef56990ee62d</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[cucumber]]></category>
            <dc:creator><![CDATA[Ankita Bhattacharjee]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 09:27:55 GMT</pubDate>
            <atom:updated>2026-10-03T09:27:55.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05hDjLcmEbiIzL7vXT3CKQ.png" /></figure><p><em>If you’ve ever opened two test reports to answer one simple question, you know the feeling.</em></p><p>That was us for a while. In my last article, I wrote about cutting our regression run from 6.5 hours to about 90 minutes by running feature files in parallel. A few scenarios couldn’t share a room with the others, so we tagged them @sequential and ran them on their own.</p><p>I promised a separate article on the Jenkins pipeline behind it. This is that article.</p><h3>The problem: two lanes, two reports</h3><p>Splitting the suite fixed the speed. It also made a small mess.</p><p>Two groups meant two reports. We also ended up with two Jenkins jobs, one for each group. So a simple question like “how many scenarios ran last night, and how many failed?” meant opening both reports and doing the math yourself.</p><p>That got old quickly. We wanted one job and one report.</p><h3>The fix: four pieces</h3><p>It came down to four pieces:</p><ol><li>Two Maven profiles, one for each group.</li><li>Separate test runners, so each group writes its own result files.</li><li>One Jenkins pipeline with two stages.</li><li>A final step that merges the results into one report.</li></ol><h3>Step 1: give each group its own Maven profile</h3><p>We added two profiles to the pom, sequential-scenarios and parallel-scenarios. Each one tells Surefire which runner to pick up and which to ignore.</p><p>Here’s the sequential one:</p><pre>&lt;profile&gt;<br>  &lt;id&gt;sequential-scenarios&lt;/id&gt;<br>  &lt;build&gt;<br>    &lt;plugins&gt;<br>      &lt;plugin&gt;<br>        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>        &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>        &lt;version&gt;2.22.0&lt;/version&gt;<br>        &lt;configuration&gt;<br>          &lt;includes&gt;<br>            &lt;include&gt;com.example.tests.SequentialProfileTestRunner.java&lt;/include&gt;<br>          &lt;/includes&gt;<br>          &lt;excludes&gt;<br>            &lt;exclude&gt;com.example.tests.ParallelProfileTestRunner.java&lt;/exclude&gt;<br>            &lt;exclude&gt;com.example.tests.FailedScenariosRunner.java&lt;/exclude&gt;<br>          &lt;/excludes&gt;<br>        &lt;/configuration&gt;<br>      &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>  &lt;/build&gt;<br>&lt;/profile&gt;</pre><p>The parallel one looks almost the same. It picks up ParallelProfileTestRunner, ignores the other two runners, and adds the parallel settings from my first article (parallel and useUnlimitedThreads).</p><p>Those includes and excludes matter. Without them, one run could quietly pick up the other group’s runner.</p><h3>Step 2: separate runners, separate result files</h3><p>We now have four runners:</p><ul><li>BaseTestRunner</li><li>ParallelProfileTestRunner</li><li>SequentialProfileTestRunner</li><li>FailedScenariosRunner</li></ul><p>The base runner holds what everyone shares: the feature path, the glue packages and the setup steps.</p><pre>@RunWith(Cucumber.class)<br>@CucumberOptions(<br>    plugin = {&quot;pretty&quot;, &quot;html:target/cucumber-html-reports&quot;},<br>    features = &quot;src/test/resources/features&quot;,<br>    glue = {<br>        &quot;com/example/tests/backend/stepdefinitions&quot;,<br>        &quot;com/example/tests/frontend/stepdefinitions&quot;,<br>        &quot;com/example/tests/backend/utilities&quot;<br>    },<br>    monochrome = true)<br>public class BaseTestRunner {<br>}</pre><p>The parallel and sequential runners extend it and add only their own result files:</p><pre>@RunWith(Cucumber.class)<br>@CucumberOptions(<br>    plugin = {<br>        &quot;junit:target/cucumber-xml-reports/ParallelCucumber.xml&quot;,<br>        &quot;json:target/cucumber-json-reports/ParallelCucumber.json&quot;,<br>        &quot;rerun:target/parallel-rerun.txt&quot;<br>    })<br>public class ParallelProfileTestRunner extends BaseTestRunner {<br>}</pre><p>The sequential runner looks the same, with SequentialCucumber.xml, SequentialCucumber.json and sequential-rerun.txt.</p><p>The file names matter more than they look. If both runners wrote to the same file, the second stage would likely overwrite the first, and half our results would disappear.</p><p>The fourth runner, FailedScenariosRunner, stands on its own. It re-runs failed scenarios (generated by cucumber-rerun plugin).</p><h3>Step 3: two stages, one pipeline</h3><p>The pipeline runs the sequential group first and the parallel group second. The tag expressions come in as job parameters, so we can change what runs without touching the code. (I’ve simplified the parameters here.)</p><pre>stage(&#39;Run scenarios sequentially&#39;) {<br>    environment {<br>        QA_CRED = credentials(&#39;qa-test-user&#39;)<br>    }<br>    steps {<br>        catchError(stageResult: &#39;FAILURE&#39;, buildResult: &#39;SUCCESS&#39;) {<br>            bat &quot;&quot;&quot;<br>                mvn clean test -Psequential-scenarios -Denv=${params.ENV_ALIAS} -Dbrowser=${params.BROWSER} -Dcucumber.options=&quot;--tags &#39;${params.SEQUENTIAL_TAGS}&#39;&quot;<br>            &quot;&quot;&quot;<br>        }<br>    }<br>}<br><br>stage(&#39;Run scenarios in parallel&#39;) {<br>    environment {<br>        QA_CRED = credentials(&#39;qa-test-user&#39;)<br>    }<br>    steps {<br>        bat &quot;&quot;&quot;<br>            mvn test -Pparallel-scenarios -Denv=${params.ENV_ALIAS} -Dbrowser=${params.BROWSER} -Dcucumber.options=&quot;--tags &#39;${params.PARALLEL_TAGS}&#39;&quot;<br>        &quot;&quot;&quot;<br>    }<br>}</pre><p>Two small details do a lot of work here.</p><p>First, Jenkins normally skips the remaining stages once a stage fails. We wanted the parallel group to run no matter how the sequential group went. catchError marks the first stage as failed but lets the build carry on.</p><p>Second, look at the Maven commands. The first stage uses mvn clean test. The second uses plain mvn test. If the second stage cleaned the target folder, it would wipe the first stage&#39;s results, and we need both for the final report.</p><h3>Step 4: one report at the end</h3><p>After both stages finish, a post { always } block builds the combined report and sends the email. It runs even when tests fail, which is exactly when you need it.</p><pre>post {<br>    always {<br>        script {<br>            def summary = junit &#39;target/cucumber-xml-reports/*.xml&#39;<br>            if (summary.getTotalCount() == 0) {<br>                emailext attachmentsPattern: &#39;target/setup.log&#39;,<br>                         body: &#39;No tests ran. The build failed in the setup steps.&#39;,<br>                         subject: &#39;[Jenkins Build] UI automation results: setup failed&#39;,<br>                         mimeType: &#39;text/html&#39;,<br>                         recipientProviders: [[$class: &#39;DevelopersRecipientProvider&#39;]]<br>            } else {<br>                cucumber fileIncludePatterns: &#39;target/cucumber-json-reports/*.json&#39;<br>                emailext body: &#39;${SCRIPT, template=&quot;groovy-html-refactor.template&quot;}&#39;,<br>                         mimeType: &#39;text/html&#39;,<br>                         subject: &#39;[Jenkins Build] UI automation results&#39;,<br>                         recipientProviders: [[$class: &#39;DevelopersRecipientProvider&#39;]]<br>            }<br>        }<br>    }<br>}</pre><p>The merging is done by a file pattern. Both runners write JSON into target/cucumber-json-reports/, so *.json matches the parallel file and the sequential file. The reporting step reads every match and builds one report.</p><p>The junit step does the same with the XML files, so the total count covers both groups.</p><p>That count has a second job. If it’s zero, no test ran, which usually means the setup steps broke. In that case we skip the report and email the setup log instead. An empty report isn’t much help when the real problem is in setup.</p><h3>The result: one report, one job</h3><p>We now get one combined report, so the total number of scenarios is easy to track. And we need only one Jenkins job instead of two.</p><h3>What I’d tell anyone trying this</h3><p>Three things are easy to get wrong:</p><ul><li>Give each group its own result file names. Otherwise one run overwrites the other.</li><li>Run clean only in the first stage. A second clean throws away the first stage&#39;s results.</li><li>Email the setup log when no tests ran. An empty report just sends people on a hunt.</li></ul><p>One piece is not covered in this article. Our UI tests sometimes failed in Jenkins and then passed when we ran them locally. The two rerun files you saw above are how we re-run those failures automatically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef56990ee62d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cutting a 6.5-Hour Regression to 90 Minutes, Even With Tests That Couldn’t Share]]></title>
            <link>https://medium.com/@anks2906/how-we-cut-a-6-5-hour-regression-suite-down-to-90-minutes-ee068348218e?source=rss-35994b380e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee068348218e</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[cucumber]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[maven]]></category>
            <dc:creator><![CDATA[Ankita Bhattacharjee]]></dc:creator>
            <pubDate>Fri, 25 Sep 2026 15:18:56 GMT</pubDate>
            <atom:updated>2026-10-04T13:54:19.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bM8DlH4bw__4v0_XD_Gu4A.png" /></figure><p><em>A few years ago, our nightly regression run took six and a half hours. We got it down to about ninety minutes. Here’s how we did it, and the three things that broke along the way.</em></p><p>If you’ve ever opened your laptop in the morning to find the nightly build still running, you know the feeling. The coffee isn’t even ready and the day already feels behind.</p><p>That was our team’s life for a while. I joined the project in 2021 and was still finding my way around the framework. And what better way for a newbie to contribute than to analyze the regression results, right? Only, I’d spend half the day just waiting for the reports to arrive.</p><p>This is the story of how we fixed it: mostly by changing a few lines of Maven config, and then spending a lot longer on the tests that didn’t like running together.</p><h3>The problem: a nightly build that ran into the morning</h3><p>Our regression suite had around <strong>1,100 Cucumber scenarios</strong>. Run one after another, they took roughly <strong>6 hours 30 minutes</strong>.</p><p>On its own, that might have been okay. But regression wasn’t our only heavy suite. Several big suites were queued up every night, and they often weren’t finished when business hours started.</p><p>That meant:</p><p>• Developers started the day without fresh test results.</p><p>• Failures were found late, when people were already busy with new work.</p><p>• “Nightly” was starting to feel more like “sometime tomorrow.”</p><p>We needed the suites to finish faster, without rewriting 1,100 scenarios.</p><h3>The obvious fix: run feature files in parallel</h3><p>The idea was simple, and plenty of teams already do it. If our tests didn’t depend on each other, why were they waiting in one long line?</p><p>We were already using Maven, so we added a <strong>Maven profile</strong> that tells the Surefire plugin to run tests in parallel:</p><pre>&lt;profiles&gt;<br>  &lt;profile&gt;<br>    &lt;id&gt;parallel-scenarios&lt;/id&gt;<br>    &lt;build&gt;<br>      &lt;plugins&gt;<br>        &lt;plugin&gt;<br>          &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;<br>          &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>          &lt;version&gt;2.22.0&lt;/version&gt;<br>          &lt;configuration&gt;<br>            &lt;parallel&gt;methods&lt;/parallel&gt;<br>            &lt;useUnlimitedThreads&gt;true&lt;/useUnlimitedThreads&gt;<br>          &lt;/configuration&gt;<br>        &lt;/plugin&gt;<br>      &lt;/plugins&gt;<br>    &lt;/build&gt;<br>  &lt;/profile&gt;<br>&lt;/profiles&gt;</pre><p>Two settings do the work:</p><p>• <em>parallel </em>turns on parallel running. With our setup (Cucumber on JUnit 4), this ran <strong>feature files</strong> in parallel. Scenarios inside a single feature file still ran one after another.</p><p>• <em>useUnlimitedThreads </em>lets Surefire use as many threads as it needs.</p><p>We put this in a profile instead of the main build so parallel runs were opt-in. To use it, you add -P and the profile name:</p><pre>mvn clean test -Pparallel-scenarios</pre><p>That’s all the setup. No changes to the feature files or the step code.</p><h3>The result: 6.5 hours down to about 1.5</h3><p>The regression run dropped from <strong>about 6 hours 30 minutes to about 1 hour 30 minutes</strong>. That’s roughly a 75% cut, and every one of our heavy suites got faster too.</p><p>The nightly builds finally finished at night. Mornings started with fresh results instead of a progress bar.</p><p>If the story ended here, this would be a very short article. It didn’t.</p><h3>What broke: tests that didn’t want to share</h3><p>Running tests in parallel only works when tests don’t step on each other. Some of ours did. Once several feature files were running at the same moment, we hit three kinds of clashes.</p><h3>1. Two features, one busy microservice</h3><p>Some scenarios created a new site configuration. Behind the scenes, every one of them used the <strong>same microservice</strong> for validation.</p><p>When these features ran at the same time, that service got flooded. Requests queued up and many scenarios <strong>timed out</strong>. The tests weren’t wrong. The service just couldn’t keep up with all of them at once.</p><h3>2. One test takes the site down for everyone</h3><p>Some scenarios <strong>fenced the site</strong>, which takes the UI offline on purpose.</p><p>Run alone, that’s fine. Run in parallel, every other feature using that site suddenly lost its UI mid-test. From their side, it looked like random failures.</p><h3>3. “Where did my widget go?”</h3><p>In our app, you could switch between sites after logging in, and each site loaded its own configuration and its own widgets. Some scenarios created data, say a widget, on one site. Meanwhile, another feature running in parallel <strong>switched to a different site</strong>.</p><p>Now the widget the first test expected wasn’t there anymore. Each test was fine on its own. Together, they were pulling the same shared state in different directions.</p><p>The lesson: parallel testing doesn’t create these problems. It <strong>exposes</strong> hidden dependencies that were always there, because running one test at a time was quietly protecting them.</p><h3>The workaround: a @sequential tag</h3><p>We didn’t want to lose the speed-up because of a handful of troublemakers. So instead of making everything sequential again, we split the suite in two.</p><p>1. We tagged the scenarios that couldn’t safely share with others with @sequential.</p><p>2. Everything <strong>with</strong> the tag ran first, one at a time, using a sequential-scenarios profile.</p><p>3. Everything <strong>without</strong> the tag ran next, in parallel, using the parallel-scenarios profile.</p><p>The tagged group was small, so most of the suite still got the full speed-up. The risky tests got a quiet room to themselves.</p><h3>How we ran the two groups</h3><p>We set up a Jenkins pipeline in our code with two stages: one for the sequential group, then one for the parallel group. Here’s a simplified version:</p><pre>stage(&#39;Run scenarios sequentially&#39;) {<br>  steps {<br>    catchError(stageResult: &#39;FAILURE&#39;, buildResult: &#39;SUCCESS&#39;) {<br>      bat &#39;mvn clean test -Psequential-scenarios -Dcucumber.options=&quot;--tags @sequential&quot;&#39;<br>    }<br>  }<br>}<br><br>stage(&#39;Run scenarios in parallel&#39;) {<br>  steps {<br>    bat &#39;mvn test -Pparallel-scenarios -Dcucumber.options=&quot;--tags \&#39;not @sequential\&#39;&quot;&#39;<br>  }<br>}</pre><p>Two small details matter here:</p><p>• <strong>catchError</strong> marks the first stage as failed if a test fails, but lets the build carry on. Without it, Jenkins would skip the parallel stage.</p><p>• <strong>mvn test instead of mvn clean test</strong> in the second stage keeps the first stage’s results, so we could combine both into one report at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PtilIdn4B4USkP-N7-vLCg.png" /></figure><p>The pipeline deserves its own story, so I’ll cover it in a separate <a href="https://medium.com/@anks2906/our-test-results-lived-in-two-places-heres-how-we-fixed-that-ef56990ee62d">article</a>.</p><p>And you don’t need a fancy pipeline to do this. Two separate jobs, one for each group, would work too. Even then, you’d finish far sooner than running all 1,100 scenarios in one long line.</p><p><strong>That’s the real point: a few dependent tests should never stop you from bringing parallel runs to your test automation framework.</strong> Set them aside, give them their own lane and let everything else fly.</p><p>A quick tip if you try this: decide what earns the tag. For us, the question was, “Does this scenario change something another feature might be using right now?” A shared service, the site’s availability or the selected site were all red flags.</p><h3>If I did it today</h3><p>This setup served us well, but it was built on JUnit 4 and Surefire 2.22.0, which are a few years old now. If I were starting fresh, I’d change a few things:</p><p>• <strong>Go down to scenario level.</strong> Newer Cucumber versions on the JUnit 5 Platform (cucumber-junit-platform-engine) or TestNG can run individual scenarios in parallel, not just whole feature files. More parallel units usually means a faster, more even run.</p><p>• <strong>Set a thread count instead of unlimited threads.</strong> Unlimited threads worked for us, but they can overload the test machine or the app you’re testing. A fixed number, tuned to your hardware and environment, is easier to predict.</p><p>• <strong>Design tests for isolation from day one.</strong> Each scenario should create its own data and clean up after itself. The fewer tests share state, the smaller your @sequential list gets.</p><p>The core idea still holds: find what’s safe to run together, run it together, and give the rest their own lane.</p><h3>What I’d tell anyone trying this</h3><p>• <strong>Start small.</strong> A Maven profile makes parallel runs opt-in, so you can try it without breaking the main build.</p><p>• <strong>Expect some failures, and treat them as clues.</strong> They point to hidden shared state. Fixing them makes your suite better, not just faster.</p><p>• <strong>Don’t give up the speed-up for a few bad apples.</strong> Tag them, run them separately and move on.</p><p>This was a team effort, and I’m grateful to the people I worked with on it. Figuring out <em>why</em> tests were failing was far more fun with them than it would have been alone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee068348218e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>