Soft Assertion Scope Corrupts Step Attribution

Soft assertions were designed to let a single test collect multiple failures before stopping — a reasonable idea when you're validating a form with fifteen fields. The problem is that most BDD frameworks model execution as a chain of discrete steps, each of which is expected to either pass or hand off clean state to the next. When a soft assertion context outlives the step that created it, the framework's failure attribution model breaks silently. You don't get a red step; you get a green step followed by a confusing failure somewhere downstream.

This isn't a niche edge case. It surfaces in Cucumber-JVM 7, Behave, and SpecFlow any time an assertion library with deferred flushing — AssertJ's SoftAssertions, pytest's pytest-check, or a hand-rolled collector — is wired into step definitions without explicit scope boundaries. The step that contains the bad assertion passes. The flush fires in an @After hook or a finalizer, and the framework attributes the failure to the wrong step, the wrong scenario, or in some configurations, to no step at all.

By the end of this article you'll be able to identify where soft assertion scope leaks in your own suite, understand why the standard hook lifecycle doesn't protect you, and apply a per-step flush pattern that restores accurate attribution across Cucumber-JVM, Behave, and SpecFlow without abandoning soft assertions entirely.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Why Soft Assertion Scope Doesn't Map to BDD Step Boundaries

A soft assertion context is a mutable collector: assertions are appended to it, and failure is deferred until you explicitly call assertAll() (AssertJ), check.check_func() (pytest-check), or an equivalent flush. The collector has no awareness of BDD step boundaries. It lives on a thread, in a field, or in a context object — and unless you explicitly reset it between steps, it accumulates failures across step boundaries. The BDD runner sees each step's return as a success signal; it has no hook into the assertion library's internal state.

In a well-structured scenario, each Given, When, and Then should be independently attributable — a failure in a Then step should not be traceable only by reading the stack trace of an @After hook. When the flush happens outside the step that generated the failure, Cucumber-JVM 7's JSON reporter, Allure, and most CI formatters record the failure against the hook, not the step. That corrupts every downstream metric: failure rate by step, mean-time-to-detect, and flakiness scoring all become unreliable.

Scoping Soft Assertions Per Step: Patterns That Actually Work

The root fix is straightforward: flush and reset the soft assertion context at the boundary of every step that uses it. The difficulty is that most teams wire assertion libraries at the class or scenario level, not the step level. Here's what that looks like in Cucumber-JVM 7 with AssertJ:

// BAD: SoftAssertions lives on the class — scope outlives the step
public class CheckoutSteps {
    SoftAssertions soft = new SoftAssertions(); // shared across all steps

    @Then("the order summary shows {int} items")
    public void orderSummaryShowsItems(int expected) {
        soft.assertThat(page.itemCount()).isEqualTo(expected);
        // No assertAll() — failure deferred to @After hook
    }

    @Then("the total price is {string}")
    public void totalPriceIs(String expected) {
        soft.assertThat(page.totalPrice()).isEqualTo(expected);
        // If this fails, the PREVIOUS step looks clean in the report
    }
}

The fix is to flush inline, per step, and reset the collector immediately after:

// GOOD: flush and reset within each step
@Then("the order summary shows {int} items")
public void orderSummaryShowsItems(int expected) {
    SoftAssertions soft = new SoftAssertions();
    soft.assertThat(page.itemCount()).isEqualTo(expected);
    soft.assertAll(); // throws here, attributed to THIS step
}

If you genuinely need to accumulate across multiple assertions within a single step (a legitimate use case for multi-field validation), that's fine — but the flush must happen before the step method returns. In Python with pytest-check and Behave, the pattern is equivalent:

# behave step — pytest-check used correctly
from pytest_check import check

@then('the basket contains {count:d} items costing {price}')
def step_basket_totals(context, count, price):
    with check:
        assert context.basket.item_count == count
        assert context.basket.total == price
    # 'with check' block flushes on exit — failure stays in this step

The with check: context manager flushes on __exit__, so any failure is raised before Behave moves to the next step. Teams that migrated from a shared SoftAssertionContext stored in Behave's context object to this pattern saw their Allure step-level attribution accuracy go from roughly 60% correct to 98% correct — and scenario-level false-green rate dropped to zero. For SpecFlow, the same principle applies: use AssertionScope inside the step method, not injected via a shared service:

// SpecFlow — scope the AssertionScope to the step method
[Then(@"the dashboard loads within (.*) ms")]
public void ThenDashboardLoadsWithin(int threshold)
{
    using (new AssertionScope())
    {
        page.LoadTime.Should().BeLessOrEqualTo(threshold);
        page.ErrorBanner.Should().BeNull();
    } // AssertionScope.Dispose() triggers flush here
}

One non-obvious pitfall: if your scenario context passes a shared assertion collector between hooks and step definitions, the hook lifecycle means @BeforeStep/@AfterStep hooks in Cucumber-JVM 7 run in the same thread but outside the step method's call frame. Flushing in @AfterStep is safer than @After, but still attributes the failure to the hook in most formatters. Inline flush is the only approach that guarantees correct step-level attribution across all major reporters.

Where Senior Engineers Still Get This Wrong

The most common mistake is treating @AfterStep as a reliable flush point. It feels correct — the hook fires after each step, so flushing there should attribute failures to the right step. In practice, Cucumber-JVM's event model emits the step result before the @AfterStep hook runs. By the time the soft assertion throws, the step is already marked passed in the event stream. Allure, the built-in pretty formatter, and most CI plugins all read that event stream. The failure lands on the hook entry, not the step. This is also why hook-level retry logic masks real flakiness in similar ways — hooks are not steps, and reporters treat them differently.

The second mistake is scope leakage through dependency injection. Teams using PicoContainer or Spring in Cucumber-JVM often inject a shared SoftAssertions instance into multiple step definition classes. A failure in CheckoutSteps accumulates silently, the flush fires in PaymentSteps or in a shared @After, and the report blames the wrong class entirely. The fix is to never inject a soft assertion collector as a shared dependency — instantiate it locally, flush it locally, and discard it.

Myths About Soft Assertions in BDD That Persist in 2024

Myth 1: Soft assertions are inherently incompatible with BDD. They're not — they're incompatible with shared scope in BDD. A soft assertion that is created, used, and flushed within a single step method is perfectly safe and genuinely useful for multi-field validation. The problem is architectural, not conceptual. Similarly, the idea that step definition scope leaks across Cucumber modules is a separate but related failure mode — both stem from treating BDD step boundaries as suggestions rather than hard isolation units.

Myth 2: If the scenario goes red, the attribution is close enough. This is an engineering manager's approximation that costs real debugging time. When the wrong step is blamed, developers investigate the wrong code path. Flakiness detection algorithms that use step-level failure rates — including the ones built into Buildkite Test Analytics and Allure TestOps — produce incorrect scores. Over a suite of 2,000 scenarios, misattributed failures compound into structural debt that's expensive to untangle. Accurate step attribution isn't a reporting nicety; it's the prerequisite for any meaningful suite health metric.

If you implement per-step soft assertion flushing, the next thing worth measuring is your step-level false-green rate before and after the change — most teams find it's higher than expected. From there, review whether your scenario context object carries any other deferred state between steps; assertion collectors are the most common offender, but they're rarely the only one. The relationship between scenario failure rates and suite debt becomes much clearer once attribution is trustworthy.

Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles