> This is part 1 of 7 of the full documentation (pages 1–100 of 649).
> The content is paginated: fetch every part to see all of it.
> Next part: https://testbox.ortusbooks.com/llms-full.txt/1
> Page index: https://testbox.ortusbooks.com/llms.txt

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://testbox.ortusbooks.com/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Introduction

TestBox is a next-generation testing framework based on BDD (Behavior Driven Development) and TDD (Test Driven Development), providing a clean, obvious syntax for writing tests.

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-a90ce92a389e66abe2cb347f6e09189c6a25dde4%2Ftestbox-logo-full-dark-M.png?alt=media)

**TestBox** is a modern testing framework for [BoxLang](https://www.boxlang.io) and ColdFusion (CFML), built around [behavior-driven development (BDD)](http://en.wikipedia.org/wiki/Behavior-driven_development) and designed to make tests clear and expressive. It includes BDD and xUnit testing, console and web runners, assertion and expectation libraries, and MockBox for mocking and stubbing.

{% tabs %}
{% tab title="BDD - BoxLang" %}

```java
class{

  function run(){
  	describe( "My calculator features", () => {

		beforeEach( () => {
			variables.calc = new Calculator()
		} )

		// Using expectations library
		it( "can add", () => {
			expect( calc.add(1,1) ).toBe( 2 )
		} )

		// Using assert library
		test( "it can multiply", () => {
			assertIsEqual( calc.multiply(2,2), 4 )
		} )
	} )
  }

}
```

{% endtab %}

{% tab title="xUnit - BoxLang" %}

```groovy
/**
 * My calculator features
 */
class{

	property calc;

	function setup(){
	    calc = new Calculator()
	}

	// Function name includes the word 'test'
	// Using expectations library
	function testAdd(){
	    expect( calc.add(1,1) ).toBe( 2 )
	}

	// Any name, but with a test annotation
	// Using assertions library
	@test
	function itCanMultiply(){
	    $assert.isEqual( calc.multiply(2,2), 4 )
	}
}
```

{% endtab %}

{% tab title="BDD - CFML" %}

```cfscript
component{

  function run(){
  	describe( "My calculator features", () => {

		beforeEach( () => {
			variables.calc = new Calculator()
		} );

		// Using expectations library
		it( "can add", () => {
			expect( calc.add(1,1) ).toBe( 2 )
		} );

		// Using assert library
		test( "it can multiply", () => {
			$assert.isEqual( calc.multiply(2,2), 4 )
		} );
	} );
  }

}
```

{% endtab %}

{% tab title="xUnit - CFML" %}

```cfscript
/**
 * My calculator features
 */
component{

	property calc;

	function setup(){
	    calc = new Calculator()
	}

	// Function name includes the word 'test'
	// Using expectations library
	function testAdd(){
	    expect( calc.add(1,1) ).toBe( 2 )
	}

	// Any name, but with a test annotation
	// Using assertions library
	function itCanMultiply() test{
	    $assert.isEqual( calc.multiply(2,2), 4 )
	}
}
```

{% endtab %}
{% endtabs %}

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-063893771ff35546d7f38889fb7f03e80a354eb8%2Ftestbox-suite-run.gif?alt=media" alt=""><figcaption><p>Runner</p></figcaption></figure>

## Browser Testing

Drive a real browser (Chromium, Firefox or WebKit) right from your specs. Add the `@browser` annotation to a spec, call `browse()`, and assert on what your users actually see. Powered by [bx-playwright](https://bxplaywright.boxlang.io) on BoxLang.

{% hint style="info" %}
Browser testing requires BoxLang and the bx-playwright module. Write browser specs as BoxLang classes (`.bx`) and keep them out of Lucee and Adobe runs. On BoxLang without bx-playwright they skip with an install hint, so the rest of your suite still runs.
{% endhint %}

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-7b315061d2136f658b73cc7296dcc75b4474046b%2Fbrowser-testing-demo.gif?alt=media" alt="A browser spec signing in to a demo shop and checking the dashboard"><figcaption><p>A browser spec signing in and checking the dashboard</p></figcaption></figure>

{% code title="tests/specs/browser/ShopSpec.bx" %}

```java
@baseURL( "http://localhost:8090" )
@browserProfile( "ci" )
class extends="testbox.system.BaseSpec" {

	function run() {
		describe( "Ortus Shop", () => {
			it( "signs in and shows the dashboard", () => {
				browse( ( page ) => {
					page.visit( "/" )
						.fill( "Email", "luis@ortus.com" )
						.fill( "Password", "secret" )
						.click( "Sign in" )
					expect( page ).toHavePath( "/dashboard.html" )
					expect( page ).toSee( "Welcome, Luis" )
				} )
			} )
		} )
	}

}
```

{% endcode %}

When a browser spec fails, TestBox captures the evidence for you: a **screenshot** of the page, a Playwright **trace** you can step through, and a **video** of the run, all linked right on the failing spec in your report.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-2dbc1aba6fd7321e749fbc678f1c67ba07dec08f%2Fbrowser-testing-report-attachments.png?alt=media" alt="A failing browser spec in the HTML report with its screenshot, trace and video attached"><figcaption><p>Failure screenshot, trace and video attached to the failing spec</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0be6c18ba48e8621bd4522425770dccce493932e%2Fbrowser-testing-trace-viewer.png?alt=media" alt="The Playwright trace viewer showing the failed assertion"><figcaption><p>Step through the failure in the Playwright trace viewer</p></figcaption></figure>

Then fix it and rerun only what failed with `--failed` or the **Run Failed** button. Start with the [Browser Testing guide](/browser-testing/browser-testing).

### Features At A Glance

Here is a simple listing of features TestBox brings to the table:

* BDD style or xUnit style testing
* Testing life-cycle methods
* [MockBox](http://wiki.coldbox.org/wiki/MockBox.cfm) integration for mocking and stubbing
* Mocking data library for mocking JSON/complex data and relationships
* Ability to extend and create custom test runners and reporters
* Extensible reporters, bundled with tons of them:
  * JSON
  * XML
  * JUnit XML
  * Text
  * Console
  * TAP ([Test Anything Protocol](http://testanything.org/))
  * Simple HTML
  * Min - Minimalistic Heaven
  * Raw
  * CommandBox
* [Browser testing](/browser-testing/browser-testing) with automatic failure screenshots, traces and videos
* Rerun only what failed, from the CLI (`--failed`) or the web runners (**Run Failed**)
* Asynchronous testing
* Multi-suite capabilities
* Test skipping
* Test labels and tagging
* Testing debug output stream
* Code Coverage via [FusionReactor](https://fusion-reactor.com/)
* Much more!

## Versioning

TestBox is maintained under the [Semantic Versioning](https://semver.org) guidelines as much as possible. Releases will be numbered in the following format:

```
<major>.<minor>.<patch>
```

And constructed with the following guidelines:

* bumpBreaking backward compatibility bumps the major (and resets the minor and patch)
* New additions without breaking backward compatibility bump the minor (and resets the patch)
* Bug fixes and misc changes bump the patch

## License

TestBox is open source and licensed under the [Apache 2](https://www.apache.org/licenses/LICENSE-2.0.html) License. If you use it, please try to mention it in your code or website.

* Copyright by Ortus Solutions, Corp
* TestBox is a registered trademark by Ortus Solutions, Corp

{% hint style="info" %}
The ColdBox Websites, Documentation, logo, and content have a separate license, and they are separate entities.
{% endhint %}

## Discussion & Help

* Help Group: <https://community.ortussolutions.com/c/communities/testbox/11>
* BoxTeam Slack : <https://boxteam.ortussolutions.com>

## Reporting a Bug

We all make mistakes from time to time :) So why not let us know about it and help us out? We also love pull requests, so please star us and fork us: <https://github.com/Ortus-Solutions/TestBox>

* By Jira: <https://ortussolutions.atlassian.net/browse/TESTBOX>

## Professional Open Source

![Ortus Solutions, Corp](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/oQgDZykv3VDrjtzLSAPK/ortussolutions_button.png)

TestBox is a professional open source software backed by [Ortus Solutions, Corp](https://www.ortussolutions.com/products/testbox) offering services like:

* Custom Development
* Professional Support & Mentoring
* Training
* Server Tuning
* Security Hardening
* Code Reviews
* [Much More](https://www.ortussolutions.com/services)

## Resources

* Official Site: [https://www.ortussolutions.com/products/testbox](http://www.ortussolutions.com/products/testbox)
* Current API Docs: <https://apidocs.ortussolutions.com/testbox/current>
* Help Group: <https://community.ortussolutions.com/c/communities/testbox/11>
* Source Code: <https://github.com/Ortus-Solutions/TestBox>
* Bug Tracker: <https://ortussolutions.atlassian.net/browse/TESTBOX>
* Twitter: [@ortussolutions](http://www.twitter.com/ortussolutions)
* Facebook: <https://www.facebook.com/ortussolutions>

#### HONOR GOES TO GOD ABOVE ALL

Because of His grace, this project exists. If you don't like this, don't read it, it's not for you.

> Therefore being justified by **faith**, we have peace with God through our Lord Jesus Christ: By whom also we have access by **faith** into this **grace** wherein we stand, and rejoice in hope of the glory of God. - Romans 5:5


# Release History

A brief history of TestBox

In this section, you will find the release notes for each version we release under this major version. If you are looking for the release notes of previous major versions, use the version switcher at the top left of this documentation book. Here is a breakdown of our major version releases.

## Version 7.x - March 2026

In this release, we focused on BoxLang CLI runner enhancements, real-time streaming test execution via SSE, a powerful dry run capability for spec discovery, Lucee 7 certification, and dropping Adobe 2021 support. Developers gain a wealth of new output-control and performance-analysis options directly from the CLI runner.

The **7.1** minor release builds on that foundation with a major expansion of the assertions and expectations library: grouped assertions, collection expectation modes, expectation context for richer failure messages, and dedicated matcher families for BoxLang `Set` and `Range` objects plus a data navigator for asserting against deeply nested structures.

The **7.2** minor release brings browser testing to TestBox: BoxLang specs with a `@browser` annotation drive a real browser through the [bx-playwright](https://bxplaywright.boxlang.io) module, with web-first browser matchers and the screenshots, traces and videos of failures attached to the spec. Every suite, on every engine, also gains spec attachments, spec retries and a **Run Failed** option, plus BoxLang runner options to start a web server for the run. The **HTML reporters** get a complete new look, with light and dark themes, keyboard navigation and **Ask AI**, which hands any failure to ChatGPT, Claude or your coding agent in one click. It also adds the **Agent reporter**, a compact JSON reporter built for AI agents and automation that reports the totals plus only the failing specs.

## Version 6.x - September 2024

In this release, we have dropped more legacy engines and added full support for not only running TestBox in [BoxLang](https://www.boxlang.io/), but writing every spec in [BoxLang](https://www.boxlang.io/). We have added tons of bug fixes and major improvements but also a great CLI runner for BoxLang.

## Version 5.x - May 2023

In this release, we have dropped legacy engines and added support for the [BoxLang](https://www.boxlang.io) JVM language, Adobe 2023 and Lucee 6. We have also added major updates to spying and expectations. We continue in this series to focus on productivity and fluency in the Testing language in preparation for more ways to test.

## Version 4.x - April 2020

In this release, we have dropped support for legacy CFML engines and introduced the ability to mock data and relationships and build JSON documents.

## Version 3.x

In this release, we focused on dropping engine supports for legacy CFML engines. We had a major breakthrough in introducing Code Coverage thanks to the [FusionReactor](https://www.fusion-reactor.com/) folks as well. This major release also came with a new UI for all reporters and streamlined the result viewports.

## Version 2.x

This version spawned off with over 8 minor releases. We focused on taking TestBox 1 to yet a high level. Much more attention to detail and introducing modern paradigms like given-when-then. Multiple interception points, async executions, and ability to chain methods.

## Version 1.x

This was our first major version of TestBox. We had completely migrated from MXUnit, and it introduced BDD to the ColdFusion (CFML) world.


# What's New With 7.2.0

October 13, 2026

TestBox 7.2.0 brings **browser testing** to TestBox. Built on the [bx-playwright](https://bxplaywright.boxlang.io) module, BoxLang specs can now drive a real browser, assert on pages with web-first matchers, and keep the screenshots, traces and videos of failures. Around it, TestBox gains features that every test suite benefits from, on every engine: spec attachments, retries, a **Run Failed** option, and BoxLang runner options to start your web server. The HTML reporters get a complete new look and an **Ask AI** assistant for every failure, and the new **Agent reporter** lets AI agents and automation read a test run with a minimal token cost.

## Highlights

* [**Browser testing**](#browser-testing) on BoxLang with bx-playwright, turned on by a `@browser`, `@browserProfile` or `@baseURL` class annotation.
* [**Browser matchers**](#browser-matchers) such as `toSee()`, `toHavePath()` and `toBeVisible()` that wait until they pass.
* [**Spec attachments**](#spec-attachments-attach) with `attach()`, shown in the HTML, JSON, text and JUnit reports.
* [**Spec retries**](#spec-retries) per spec, per bundle or for the whole run.
* [**Run only what failed**](#run-only-what-failed) with a **Run Failed** button, `--failed` and `TestResult.getFailedTargets()`.
* [**`--web-server`**](#boxlang-runner-web-server) runner options that start your application for the run.
* [**New HTML reporters**](#a-new-look-for-the-html-reporters) with light and dark themes, inline screenshots and **Ask AI** on every failure.
* [**Agent reporter**](#agent-reporter), a token-efficient JSON reporter for AI agents and automation.

***

## Browser Testing

{% file src="/files/LNjLkDmtdGb7POERERVb" %}
Browser testing in TestBox 7.2, in 80 seconds
{% endfile %}

{% hint style="info" %}
Browser specs and the browser matchers require BoxLang and the bx-playwright module. Write browser specs as BoxLang classes (`.bx`) and keep them out of Lucee and Adobe runs, where the browser annotations do nothing. On BoxLang without bx-playwright, `browse()` skips the running spec with an install hint: `bx-playwright is not installed: install-bx-module bx-playwright`.
{% endhint %}

Turn browser support on with a class annotation, `@browser`, `@browserProfile` or `@baseURL`, on any spec whose class, or a class it extends, carries it. No special base class is needed. Then call `browse()`: every declared closure argument gets a fresh page in its own isolated browser context, and the bundle shares one browser that the runner closes after the bundle, even when an `afterAll()` throws.

```java
@baseURL( "http://localhost:8080" )
@browserProfile( "ci" )
class extends="testbox.system.BaseSpec" {

    function run() {
        describe( "Login", () => {
            it( "signs in", () => {
                browse( ( page ) => {
                    page.visit( "/login" )
                        .fill( "Email", "luis@ortus.com" )
                        .fill( "Password", "secret" )
                        .click( "Sign in" )
                    expect( page ).toHavePath( "/dashboard" )
                    expect( page ).toSee( "Welcome" )
                } )
            } )
        } )
    }

}
```

* `@browser`, `@browserProfile` and `@baseURL` class annotations turn browser support on, and are inherited from parent classes: put `@browser` on your project base spec and its children can browse, and `@browser( false )` opts a child out. It works for BDD and xUnit bundles on any base class, such as `testbox.system.BaseSpec` or a ColdBox `BaseTestCase`.
* The runner mixes `browse()`, `browserAvailable()`, `ensureBrowserInstalled()`, `getBrowserSupport()` and `closeBrowser()` into the spec, adds `this.playwright()` and registers the browser matchers. Public methods your spec declares itself are kept; a private method with the same name is replaced.
* `testbox.system.BrowserSpec` is an optional base class that carries `@browser`.
* The browser of the bundle profile is installed on first use, unless the profile uses a branded channel such as `chrome` or `msedge` (it needs network access, and Linux needs the system libraries from `bxplaywright install chromium --with-deps`). Use `@browserAutoInstall( false )` to require a pre-installed browser, or `ensureBrowserInstalled()` to install it yourself. TestBox needs a bx-playwright version that provides `playwrightEnsureBrowser()`, the first stable release or later.
* `browse( callback, options )` with one page per declared argument, for multi-user flows.
* `this.playwright()` for the bundle's bx-playwright manager, and `browserAvailable()` for skip constraints.
* The logic lives in `testbox.system.browser.BrowserSupport`, usable from any BoxLang code.

Read the [Browser Testing guide](/browser-testing/browser-testing).

## Browser Matchers

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0fdb43198fd3a0acc391a07e80ca2e487e9195b0%2Ftestbox-browser-matchers.gif?alt=media" alt="Browser matchers in a spec, a browser waiting for the page, and a failing toHaveCount() message"><figcaption><p>Browser matchers wait for the page and explain their failures</p></figcaption></figure>

Nine web-first matchers for bx-playwright pages and locators, each with its `not` form. They retry until they pass or the assertion timeout expires, and fail with Playwright's expected, received and call log message.

```java
expect( page ).toHaveTitle( "Dashboard" )
expect( page ).toHaveURL( page.regex( "/orders/\d+$" ) )
expect( page ).toHavePath( "/dashboard" )
expect( page ).toSee( "Welcome" )
expect( page.locator( "h1" ) ).toHaveText( "Your Orders" )
expect( page.locator( "@menu" ) ).toBeVisible()
expect( page.locator( ".spinner" ) ).toBeHidden()
expect( page.locator( ".cart li" ) ).toHaveCount( 2 )
expect( page.byLabel( "Email" ) ).toHaveValue( "luis@ortus.com" )
```

Browser bundles register them for you; any other BoxLang spec can use `addMatchers( new testbox.system.browser.BrowserMatchers() )`. See [Browser Matchers](/browser-testing/browser-matchers).

## Spec Attachments: `attach()`

Every spec can attach files to its result, on every engine: `attach( path, type = "file", name = "" )`. A failed `browse()` attaches the screenshots, trace and videos bx-playwright kept.

{% tabs %}
{% tab title="BoxLang" %}

```java
it( "renders the PDF", () => {
    var pdf = getTempDirectory() & "report.pdf"
    new models.Reports().monthly( pdf )
    attach( pdf, "file", "Monthly report" )
} )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
it( "renders the PDF", function(){
    var pdf = getTempDirectory() & "report.pdf";
    new models.Reports().monthly( pdf );
    attach( pdf, "file", "Monthly report" );
} );
```

{% endtab %}
{% endtabs %}

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-cc692d96ffea42c33f3428bb8907159a6f552b5d%2Ftestbox-failure-artifacts.gif?alt=media" alt="A failed browser spec with its screenshot in the HTML report and its Playwright trace"><figcaption><p>The screenshot, trace and video of a failed browser spec</p></figcaption></figure>

Attachments land in the new `attachments` array of the spec stats. The JSON report includes them, the HTML reports show screenshots inline as thumbnails that open full size and link the other files, the text, console and stream outputs list them under failed specs, and the JUnit and ANT JUnit reports add one `[[ATTACHMENT|path]]` line per file in `<system-out>`, the format the Jenkins JUnit Attachments plugin and GitLab understand. See [Attachments](/browser-testing/attachments).

## Spec Retries

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-9791ada493be88ca8cd87cff0321c9dff25280f5%2Ftestbox-spec-retries.gif?alt=media" alt="A spec with retries = 2 that passes on its second attempt"><figcaption><p>A flaky spec passing on its second attempt</p></figcaption></figure>

Rerun a failing or erroring spec, with its `beforeEach()` and `afterEach()` (or `setup()` and `teardown()`), up to N more times, on every engine:

{% tabs %}
{% tab title="BoxLang" %}

```java
@retries( 1 )
class extends="testbox.system.BaseSpec" {

    function run() {
        describe( "Payment gateway", () => {
            it( title = "charges a card", body = () => {
                expect( gateway.charge( 100 ).status ).toBe( "succeeded" )
            }, retries = 3 )
        } )
    }

}
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
component extends="testbox.system.BaseSpec" retries="1" {

    function run(){
        describe( "Payment gateway", function(){
            it( title = "charges a card", body = function(){
                expect( gateway.charge( 100 ).status ).toBe( "succeeded" );
            }, retries = 3 );
        } );
    }

}
```

{% endtab %}
{% endtabs %}

* A `retries` argument on `it()`, `fit()` and `xit()`, a `retries` bundle annotation, a `retries` method annotation for xUnit tests, and a global `retries` runner option (`--retries=N` on the BoxLang runner).
* The spec value wins over the bundle annotation, which wins over the global option. Skipped specs are never retried.
* The new `attempts` spec stat counts the runs, and reporters show `(passed after 2 attempts)`.

See [Retries](/browser-testing/retries).

## Run Only What Failed

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-2124c3f1742a323094cb6cba695361f5119d04a2%2Ftestbox-run-failed.gif?alt=media" alt="The Run Failed button of the HTML report and ./testbox/run --failed rerunning one spec"><figcaption><p>Run Failed in the report and --failed in the CLI</p></figcaption></figure>

* **HTML reports:** the Simple, Min, Dot and Doc reports show a **Run Failed (N)** button next to **Run All** when something failed. The link is built from the report, so the web runners keep no state.
* **BoxLang runner:** every run writes `{reportpath}/.testbox-failed.json` with the bundles and spec ids that failed or errored, and `./testbox/run --failed` reruns only those.
* **From code:** `TestResult.getFailedTargets()` returns `{ bundles, specs, bundleErrors }` on every engine.

```bash
./testbox/run                # 3 specs fail, .testbox-failed.json lists them
./testbox/run --failed       # reruns only those 3
```

Bundles that failed outside of a spec (`beforeAll()`, `afterAll()`) go to `bundleErrors`: they are listed, not rerun. When the file is missing or lists nothing, `--failed` prints a message and runs nothing. See [Rerun What Failed](/browser-testing/running-browser-tests#rerun-what-failed-failed).

## BoxLang Runner: `--web-server`

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-fc2b174a7997b1ffce4ac7a82b60cedfed0f024c%2Ftestbox-web-server.gif?alt=media" alt="The BoxLang runner starting a MiniServer, running a browser spec and stopping the server"><figcaption><p>The BoxLang runner starting and stopping your web server</p></figcaption></figure>

Start your application before the tests, wait until it answers, and stop it with its child processes afterwards:

```bash
./testbox/run --web-server="boxlang-miniserver --port 8080" --web-server-url=http://localhost:8080 --web-server-timeout=60
```

The runner exits with code 1 when the server does not answer in time. The URL becomes the default `baseURL` of browser bundles. See [Running Browser Tests](/browser-testing/running-browser-tests).

***

## A New Look For The HTML Reporters

The `Simple`, `Min`, `Dot` and `Doc` reporters have been rebuilt and made reactive thanks to AlpineJS, with light and dark themes on the TestBox palette and the new TestBox logos. They keep every feature they had, and they are still fully inlined, so reports run airgapped. A page also went from about 1.4 MB to about 0.45 MB when fully loaded.

{% embed url="<https://youtu.be/FNiiAzqS7tU>" %}

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-818603d285b2c6afb9b098d51cabcb9c81d66060%2Freporters-simple-failures-light.png?alt=media" alt="The Simple reporter in light mode"><figcaption><p>Simple, light mode</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-14cbc65da60d8fd00283608bf7184b06bfa1df4a%2Freporters-simple-failures-dark.png?alt=media" alt="The Simple reporter in dark mode"><figcaption><p>Simple, dark mode</p></figcaption></figure>

### At A Glance

* **The verdict first.** A green or red banner with the totals, a proportion bar and status filters, so a failing run can not be missed. A bundle that could not run gets its own alert above it.
* **Light, dark and system themes**, applied before the page paints and remembered in your browser.
* **Keyboard navigation.** Press `F` to jump to the next failure and `/` to search.
* **Filters everywhere.** Filter the whole report or a single bundle by status, and search by name.
* **Highlighted code** for BoxLang and CFML, with the failing line marked.
* **Run links** on every bundle, suite and spec. They are plain links, so a refresh runs them again.
* **Run All and Run Failed.** When something failed, a **Run Failed (N)** button reruns only those specs. The link is built from the report, so the web runner keeps no state. See [Run Only What Failed](#run-only-what-failed).
* **Dot opens a drawer** with the details, the code and Ask AI, instead of an `alert()`. **Doc** has a bundle navigation.
* **Responsive**, so a CI artifact is readable on a phone.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-c10e0773f384f934e7e76d60111d07f8d9b2984e%2Freporters-demo-next-failure.gif?alt=media" alt="Pressing F to jump between failures"><figcaption><p>Press <code>F</code> to jump from failure to failure</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-42884af5a0760de99e93dda542dcecea98e4771a%2Freporters-demo-dot-drawer.gif?alt=media" alt="The Dot reporter opening a drawer"><figcaption><p>Dot opens the details in a drawer</p></figcaption></figure>

### Screenshots In The Report

Image attachments, such as failure screenshots, show as thumbnails that open full size. They are embedded in the page, so they work over http and in saved reports. Images up to the new `inlineImageMaxKB` reporter option (default `2048`, `0` turns it off) are embedded, larger ones stay links. A trace attachment offers a **Copy show-trace command** button.

```java
new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = { type : "simple", options : { inlineImageMaxKB : 512 } }
).run()
```

See [Screenshots in the HTML Reports](/browser-testing/attachments#screenshots-in-the-html-reports).

### Ask AI

Every failure and error has an **Ask AI** menu. It builds a prompt with the spec, the message, the code around the failing line, the first stack frames and the command that runs only that spec again. You can copy it, preview it, open it in ChatGPT or Claude, or copy the failure as JSON for a coding agent. **Copy all failures for AI** builds one prompt for the whole run.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b82609300f0519495566d2a7d27c1cdf28b6c9f5%2Freporters-demo-ask-ai.gif?alt=media" alt="Opening the Ask AI menu and previewing the prompt"><figcaption><p>Ask AI menu and prompt preview</p></figcaption></figure>

Ask AI is on by default. Nothing leaves the page until you click a provider, and the first time you do, the page tells you what will happen and waits for your confirmation. Use the `aiAssist`, `aiProviders`, `aiContextLines`, `aiStackFrames` and `aiPrompt` reporter options to configure it, or `?aiAssist=false` to switch it off for a run. See [Ask AI options](/digging-deeper/reporters/html-reporters#options).

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-87695a327de18da903f65c2c0f7aa136a0b147e7%2Freporters-ai-notice.png?alt=media" alt="The first-use notice"><figcaption><p>The first-use notice</p></figcaption></figure>

### Reports From Code

The `urlParams` reporter option sets request params such as `editor` and `aiAssist` when you produce a report from code and there is no `url` scope, for example with the BoxLang CLI:

```java
reporter = { type : "simple", options : { urlParams : { editor : "idea", aiAssist : "false" } } }
```

### Upgrade Notes

{% hint style="warning" %}
**Changed in TestBox 7.2:** the `url.fullPage` switch was removed. An HTML reporter always returns a complete page. If you embedded a reporter in your own page, include it in an `<iframe>` or use the `JSON` reporter and render the data yourself.
{% endhint %}

{% hint style="info" %}
The report templates now keep only markup. Their logic lives in `system/reports/ReportHelper.cfc` and `BaseHTMLReporter.cfc`. The reporters share one base class, `BaseHTMLReporter`. The inlined front-end libraries are rebuilt from `build/vendor` with `box run-script assets:update`.
{% endhint %}

Everything about the new reporters is documented in [HTML Reporters](/digging-deeper/reporters/html-reporters).

***

## Agent Reporter

The new `Agent` reporter returns a single minified JSON line with the totals and only the specs that failed or errored. A passing run is a few dozen tokens, where the `JSON` reporter returns the full result set.

{% tabs %}
{% tab title="BoxLang" %}
{% code title="BoxLang CLI runner" %}

```bash
./testbox/run --reporter=agent
```

{% endcode %}

{% code title="Programmatic" %}

```java
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.AgentReporter",
        options : { maxFailures : 10 }
    }
)
println( testbox.run() )
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="Programmatic" %}

```cfscript
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.AgentReporter",
        options : { maxFailures : 10 }
    }
);
writeOutput( testbox.run() );
```

{% endcode %}
{% endtab %}
{% endtabs %}

```json
{"ok":false,"totals":{"pass":120,"fail":2,"error":1,"skipped":3,"specs":126,"ms":4210},"failures":[{"bundle":"tests.specs.FooTest","spec":"Foo > can add","status":"failed","message":"Expected [4] but received [3]","at":"tests/specs/FooTest.cfc:42"}],"truncated":0}
```

You can control the amount of detail with the `detail`, `maxFailures`, `maxMessageLength`, `includeStack`, `stackDepth`, `includeSkipped` and `includeDebug` options. See the full reference in [Reporters](/digging-deeper/reporters#agentreporter---token-efficient-output-for-ai-agents).

## Changes

### Playwright Assertion Failures Are Failures

{% hint style="warning" %}
**Changed in TestBox 7.2:** a `Playwright.AssertionFailed` exception now counts as a spec **failure**, like `TestBox.AssertionFailed`, in BDD specs and xUnit tests, keeping its message and detail. It used to count as an error. Other `Playwright.*` exceptions, such as `Playwright.Timeout`, still count as errors.
{% endhint %}

### xUnit Failure Detail

xUnit failures now also record the failure detail in the spec stats, as BDD failures already did.

## Fixes

* **Bundle error badge.** The bundle badge of the HTML reporters showed a negative error count (`-1 error`) when a bundle threw outside a spec, for example in `beforeAll()`. It now shows none.
* **`run` script quoting.** The `run` launcher script now quotes its arguments, so runner options with spaces, such as a `--web-server` command, reach the BoxLang runner intact.
* **Specs that do not extend `BaseSpec`.** TestBox mixes `testbox.system.BaseSpec` into a spec that does not extend it. On BoxLang those specs errored: the mixed in BaseSpec missed its private state, three of its methods declared a `BaseSpec` return type, and `expect()` resolved `Expectation` relative to the spec. They run again.
* **JUnit reports without `bx-esapi`.** The `JUnit` and `ANTJunit` reporters failed on BoxLang when the `bx-esapi` module was not installed, because they encode attributes with `encodeForXMLAttribute()`. They now fall back to `xmlFormat()`, also on Adobe with full null support.

## Release Notes

### New Features

| #                                                                      | Title                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [TESTBOX-469](https://ortussolutions.atlassian.net/browse/TESTBOX-469) | New `AgentReporter` (`reporter=agent`): a token-efficient JSON reporter for AI agents, with the `detail`, `maxFailures`, `maxMessageLength`, `includeStack`, `stackDepth`, `includeSkipped` and `includeDebug` options |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | Browser testing with bx-playwright: `@browser`, `@browserProfile` and `@baseURL` annotations, optional `BrowserSpec`, `browse()`, one browser per bundle closed by the runner, failure artifacts attached to the spec  |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | Browser matchers: `toHaveTitle()`, `toHaveURL()`, `toHavePath()`, `toSee()`, `toHaveText()`, `toBeVisible()`, `toBeHidden()`, `toHaveCount()` and `toHaveValue()`, with their `not` forms                              |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | `attach( path, type, name )` and the `attachments` spec stat, in the JSON, HTML, text, console, stream, JUnit and ANT JUnit reports                                                                                    |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | Spec retries: `retries` on `it()`, `fit()` and `xit()`, bundle and xUnit method annotations, global `retries` option and `--retries=N`, with the `attempts` spec stat                                                  |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | Run only what failed: `TestResult.getFailedTargets()`, the **Run Failed** button and the BoxLang runner `--failed` option                                                                                              |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | BoxLang runner `--web-server`, `--web-server-url` and `--web-server-timeout` options                                                                                                                                   |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | Ask AI on failures, with the `aiAssist`, `aiProviders`, `aiContextLines`, `aiStackFrames` and `aiPrompt` reporter options                                                                                              |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | `urlParams` reporter option for reports produced from code                                                                                                                                                             |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | Inline image attachments in the HTML reports and the `inlineImageMaxKB` reporter option                                                                                                                                |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | `build/vendor` rebuilds the inlined front-end libraries with `box run-script assets:update`                                                                                                                            |

### Improvements

| #                                                                      | Title                                                                                                                                                 |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | HTML reporters rebuilt on Bootstrap 5.3, Bootstrap Icons, Alpine and Prism, with light and dark themes, new logos and pages about a third of the size |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | The verdict first: a sticky banner with counts, a proportion bar and status filters, and an alert for bundle exceptions                               |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | Re-run links are plain links that carry only `testBundles`, `testSuites` or `testSpecs`                                                               |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | `Dot` opens a drawer, `Doc` has a bundle navigation, and the status chips of `Min` and `Dot` filter                                                   |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | Report templates keep only markup; logic moved to `ReportHelper.cfc` and `BaseHTMLReporter.cfc`                                                       |
| [TESTBOX-470](https://ortussolutions.atlassian.net/browse/TESTBOX-470) | `Playwright.AssertionFailed` counts as a spec failure, not an error                                                                                   |
|                                                                        | xUnit failures record the failure detail in the spec stats                                                                                            |

### Bugs

| #                                                                      | Title                                                                                                                      |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | The bundle badge of the HTML reporters showed `-1 error` when a bundle threw outside a spec                                |
|                                                                        | The `run` script now quotes its arguments                                                                                  |
|                                                                        | The `JUnit` and `ANTJunit` reporters failed on BoxLang without `bx-esapi`                                                  |
|                                                                        | Specs that do not extend `testbox.system.BaseSpec` run again ([#223](https://github.com/Ortus-Solutions/TestBox/pull/223)) |

### Removed

| #                                                                      | Title                                                                               |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| [TESTBOX-471](https://ortussolutions.atlassian.net/browse/TESTBOX-471) | The `url.fullPage` switch of the HTML reporters: a report is always a complete page |


# What's New With 7.1.0

September 10, 2026

TestBox 7.1.0 introduces a significant upgrade to the assertions and expectations library, adding grouped assertions, collection expectation modes, rich failure diagnostics, and a suite of new matchers inspired by JUnit 5 and Jasmine.

***

## Expectation Context: `withContext()`

Add semantic context to any expectation so failure messages include identifying information. Works with all matchers, negated matchers, and custom matchers.

```javascript
it( "validates a user record", () => {
    expect( user.age )
        .withContext( "user.age" )
        .toBeGT( 0 )

    expect( user.email )
        .withContext( "user.email" )
        .toMatch( "@" )
} )
```

***

## Collection Expectation Modes

Three new collection modes complement the existing `expectAll()`.

### `expectAny()`

Passes when at least one element in the collection passes the chained matcher.

```javascript
expectAny( products ).toSatisfy( p => p.onSale )
```

### `expectSome()`

Passes when a bounded number of elements pass. `max = 0` means no upper bound.

```javascript
expectSome( users, min = 2, max = 5 ).toSatisfy( u => u.role == "admin" )
expectSome( items, min = 3 ).toSatisfy( i => i.stock > 0 )
```

### `expectNone()`

Passes when zero elements pass the chained matcher.

```javascript
expectNone( users ).toSatisfy( u => u.banned )
```

### Improved `expectAll()` Failure Messages

All collection modes now produce detailed failure summaries with pass/fail counts and per-element failure context including the element index or struct key.

```javascript
try {
    expectAll( [ 2, 4, 10, 8 ] ).toBeLT( 10 )
} catch ( any e ) {
    // e.message: "expectAll() failed: 1 of 4 element(s) did not pass the [toBeLT] expectation"
    // e.detail:  "Passed: 3 / 4\n\n[3]: The actual [10] is not less than [10]"
}
```

***

## Grouped Assertions: `assertAll()`

Run multiple assertion closures and report every failure at once — instead of stopping at the first. Non-assertion exceptions are rethrown immediately.

```javascript
it( "validates a user record completely", () => {
    assertAll( [
        () => expect( user.name ).notToBeEmpty(),
        () => expect( user.email ).toMatch( "@" ),
        () => expect( user.age ).toBeGTE( 18 ),
        () => expect( user.age ).toBeLT( 120 )
    ] )
} )
```

Using the `$assert` style:

```javascript
it( "xUnit style grouped assertions", () => {
    $assert.all(
        executables = [
            () => $assert.isTrue( true ),
            () => $assert.isEqual( 1, 2 ),
            () => $assert.notNull( javacast( "null", "" ) )
        ],
        heading = "Basic checks"
    )
} )
```

***

## New Matchers

### `toIncludeAll` / `toIncludeAny` / `toIncludeNone`

Assert that a string or array contains all, any, or none of the given needles with case-insensitive matching.

```javascript
expect( "hello world" ).toIncludeAll( [ "hello", "world" ] )
expect( "hello world" ).toIncludeAny( [ "hello", "foo" ] )
expect( "hello world" ).toIncludeNone( [ "foo", "bar" ] )
```

### `toBeTruthy` / `toBeFalsy`

Assert that a value is truthy (not false, `0`, empty string, or null) or falsy.

```javascript
expect( 42 ).toBeTruthy()
expect( "" ).toBeFalsy()
```

### `toHaveSize`

Alias for `toHaveLength()` — works on strings, arrays, structs, and queries.

```javascript
expect( "abc" ).toHaveSize( 3 )
expect( [ 1, 2 ] ).toHaveSize( 2 )
expect( { a : 1, b : 2 } ).toHaveSize( 2 )
```

### `toBeSameInstanceAs`

Assert two references point to the exact same object instance.

```javascript
var obj = { name : "test" }
expect( obj ).toBeSameInstanceAs( obj )
```

### `toThrowMatching`

Assert a function throws an exception that matches a predicate closure.

```javascript
expect( () => {
    throw( type = "FooException" )
} ).toThrowMatching( e => e.type == "FooException" )
```

***

## New Assertion BIFs

For xUnit-style testing, the following new `$assert` methods are available:

| Method                                             | Description                              |
| -------------------------------------------------- | ---------------------------------------- |
| `$assert.isTruthy( actual, message )`              | Value is truthy                          |
| `$assert.isFalsy( actual, message )`               | Value is falsy                           |
| `$assert.includesAll( target, needles, message )`  | Target contains every needle             |
| `$assert.includesAny( target, needles, message )`  | Target contains at least one needle      |
| `$assert.includesNone( target, needles, message )` | Target contains no needle                |
| `$assert.all( executables, heading )`              | Run all assertions, report every failure |

```javascript
$assert.isTruthy( "hello" )
$assert.isFalsy( 0 )
$assert.includesAll( "hello world", [ "hello", "world" ] )
$assert.includesAny( [ "a", "b" ], [ "b", "z" ] )
$assert.includesNone( "hello", [ "x", "y" ] )
```

***

## Set Expectations

TestBox now provides a comprehensive suite of set-related matchers for working with BoxLang `Set` objects. These matchers leverage the global `setOf()` function to create sets and provide powerful assertions for set operations.

### Creating Sets with `setOf()`

```javascript
var set1 = setOf( 1, 2, 3 )
var set2 = setOf( 3, 4, 5 )
var set3 = setOf( 1, 2, 3, 4, 5 )
var emptySet = setOf()
```

### `toBeASet()` / `notToBeASet()`

Assert that a value is (or is not) a Set object.

```javascript
expect( set1 ).toBeASet()
expect( [ 1, 2, 3 ] ).notToBeASet()
```

### `toEqualSet()` / `notToEqualSet()`

Assert that two sets contain the same elements, regardless of order.

```javascript
expect( setOf( 1, 2, 3 ) ).toEqualSet( setOf( 3, 2, 1 ) )
expect( setOf( 'a', 'b' ) ).toEqualSet( setOf( 'b', 'a' ) )
expect( setOf( 1, 'a', true ) ).toEqualSet( setOf( true, 'a', 1 ) )
```

### `toBeSubsetOf()` / `notToBeSubsetOf()`

Assert that all elements of the actual set are contained in the expected set.

```javascript
expect( setOf( 1, 2 ) ).toBeSubsetOf( setOf( 1, 2, 3, 4, 5 ) )
expect( setOf( 1, 2, 3, 4, 5 ) ).notToBeSubsetOf( setOf( 1, 2 ) )
```

### `toBeSupersetOf()` / `notToBeSupersetOf()`

Assert that the actual set contains all elements of the expected set.

```javascript
expect( setOf( 1, 2, 3, 4, 5 ) ).toBeSupersetOf( setOf( 1, 2, 3 ) )
expect( setOf( 1, 2, 3 ) ).notToBeSupersetOf( setOf( 1, 2, 3, 4, 5 ) )
```

### `toBeDisjointFrom()`

Assert that two sets share no common elements.

```javascript
expect( setOf( 1, 2 ) ).toBeDisjointFrom( setOf( 3, 4 ) )
```

### `toHaveUnion()` / `notToHaveUnion()`

Assert that the union of two sets equals an expected set.

```javascript
expect( setOf( 1, 2 ) ).toHaveUnion( setOf( 3, 4 ), setOf( 1, 2, 3, 4 ) )
```

### `toHaveIntersection()` / `notToHaveIntersection()`

Assert that the intersection of two sets equals an expected set.

```javascript
expect( setOf( 1, 2, 3 ) ).toHaveIntersection( setOf( 3, 4, 5 ), setOf( 3 ) )
```

### `toHaveDifference()` / `notToHaveDifference()`

Assert that the set difference (actual - expected) equals an expected result.

```javascript
expect( setOf( 1, 2, 3 ) ).toHaveDifference( setOf( 3, 4, 5 ), setOf( 1, 2 ) )
```

### `toHaveSymmetricDifference()` / `notToHaveSymmetricDifference()`

Assert that the symmetric difference (elements in either set but not both) equals an expected result.

```javascript
expect( setOf( 1, 2, 3 ) ).toHaveSymmetricDifference( setOf( 3, 4, 5 ), setOf( 1, 2, 4, 5 ) )
```

### Real-World Example: Menu Selection

```javascript
it( "validates menu selection", () => {
    var fruits = setOf( 'apple', 'banana', 'cherry' )
    var selected = setOf( 'apple', 'banana' )

    expect( selected ).toBeSubsetOf( fruits )
    expect( selected ).toHaveIntersection( fruits, setOf( 'apple', 'banana' ) )
} )
```

***

## Range Expectations (BoxLang)

TestBox now includes a full set of matchers for BoxLang `Range` objects, including containment, ordering, bounds, and step/clamp assertions.

{% hint style="info" %}
**BoxLang only.** Range features depend on BoxLang range support. On CFML engines these expectations are guarded and report unsupported behavior cleanly.

Ranges are created with the `..` operator (for example `1..10`, `..10`, `1..`, `..`) and stepped via `.step( n )`. There is no `rangeNew()` BIF.
{% endhint %}

### Core Range Matchers

* `toBeRange()`
* `toContainValue( value )`
* `toContainRange( range )`
* `toBeInRange( range )`
* `toBeBeforeRange( range )`
* `toBeAfterRange( range )`

### Range Shape And Direction

* `toBeBounded()`
* `toBeUnbounded()`
* `toBeHalfBounded()`
* `toBeIterable()`
* `toBeAscending()`
* `toBeDescending()`

### Step And Clamp

* `toHaveStep( step )`
* `toClampTo( value, expected )`

```javascript
var base = 1..10
var stepped = (0..100).step( 5 )
var chars = "a".."z"
var dates = createDate( 2024, 1, 1 )..createDate( 2024, 1, 31 )

expect( base ).toBeRange()
expect( base ).toContainValue( 5 )
expect( base ).toContainRange( 3..7 )
expect( 8 ).toBeInRange( base )

expect( stepped ).toHaveStep( 5 )
expect( base ).toClampTo( 15, 10 )
expect( dates ).toContainValue( "2024-01-15" )

expect( chars ).toBeAscending()
expect( chars ).toContainValue( "m" )
```

Equivalent native Range API examples used under these matchers:

```javascript
base.contains( 5 )
base.contains( 3..7 )
stepped.getStep()          // 5
base.clamp( 15 )           // 10
```

***

## Data Navigator Expectations

TestBox now provides a suite of matchers that leverage BoxLang's built-in `dataNavigate()` BIF to safely navigate and assert against values in nested data structures. These matchers support dot-notation, array indexes, wildcards, filters, recursive descent, and all other JSONPath-style expressions.

{% hint style="info" %}
**BoxLang only.** Data navigator features require the BoxLang runtime and are guarded at the matcher level. On CFML engines they throw `TestBox.BoxLangFeatureNotAvailable`.
{% endhint %}

### `toHavePath()` / `notToHavePath()`

Assert that a path exists (or does not exist) in a nested data structure.

```javascript
var data = {
    "app" = { "name" = "TestApp", "settings" = { "debug" = true, "port" = 8080 } },
    "users" = [ { "name" = "Alice", "age" = 30 } ]
}

expect( data ).toHavePath( "app.name" )
expect( data ).toHavePath( "app.settings.debug" )
expect( data ).toHavePath( "users[1].name" )
expect( data ).notToHavePath( "nonexistent" )
expect( data ).notToHavePath( "app.nonexistent" )
```

### `toHavePathValue()` / `notToHavePathValue()`

Assert that the value at a path matches an expected value.

```javascript
expect( data ).toHavePathValue( "app.name", "TestApp" )
expect( data ).toHavePathValue( "app.settings.port", 8080 )
expect( data ).toHavePathValue( "app.settings.debug", true )
expect( data ).toHavePathValue( "users[1].name", "Alice" )
expect( data ).notToHavePathValue( "app.name", "WrongApp" )
```

### `toHavePathType()` / `notToHavePathType()`

Assert the type of the value at a path. Supports standard types (`string`, `numeric`, `boolean`, `struct`, `array`) and common aliases (`str`, `num`, `bool`, `arr`, `obj`, `map`).

```javascript
expect( data ).toHavePathType( "app.name", "string" )
expect( data ).toHavePathType( "app.settings.port", "numeric" )
expect( data ).toHavePathType( "app.settings.debug", "boolean" )
expect( data ).toHavePathType( "app.settings", "struct" )
expect( data ).toHavePathType( "users", "array" )
expect( data ).toHavePathType( "app.settings.port", "num" )       // alias
expect( data ).notToHavePathType( "app.name", "numeric" )
```

### `toHavePathSatisfying()` / `notToHavePathSatisfying()`

Assert that the value at a path satisfies a predicate closure.

```javascript
expect( data ).toHavePathSatisfying( "app.name", name -> name == "TestApp" )
expect( data ).toHavePathSatisfying( "app.settings.port", port -> port > 1000 )
expect( data ).toHavePathSatisfying( "app.settings", settings -> settings.keyExists( "debug" ) )
expect( data ).notToHavePathSatisfying( "app.name", name -> name == "WrongName" )
```

### `path()`

Navigate to a path and return a normal `Expectation` on the value at that path. Supports chaining any matcher on the result.

```javascript
expect( data ).path( "app.name" ).toBe( "TestApp" )
expect( data ).path( "app.settings.port" ).toBeGT( 8000 )
expect( data ).path( "users" ).toHaveLength( 1 )
expect( data ).path( "nonexistent" ).toBeNull()
```

### `queryPath()`

Navigate to a path and return an `Expectation` on an array of all matching values. Fans out at wildcards, filters, and recursive descent segments.

```javascript
expect( data ).queryPath( "users[*].name" ).toHaveLength( 1 )
expect( data ).queryPath( "users[*].name" ).toInclude( "Alice" )
expect( data ).queryPath( "nonexistent" ).toBeEmpty()
```

### Real-World Example: API Response Validation

```javascript
it( "validates an API response", () => {
    var response = {
        "success" = true,
        "data" = {
            "users" = [
                { "name" = "Alice", "role" = "admin", "active" = true },
                { "name" = "Bob",   "role" = "user",  "active" = false }
            ],
            "metadata" = { "total" = 2, "page" = 1 }
        }
    }

    // Path existence
    expect( response ).toHavePath( "data.users" )
    expect( response ).notToHavePath( "data.errors" )

    // Path values
    expect( response ).toHavePathValue( "success", true )
    expect( response ).toHavePathValue( "data.metadata.total", 2 )

    // Path types
    expect( response ).toHavePathType( "data.users", "array" )
    expect( response ).toHavePathType( "data.metadata.total", "numeric" )

    // Predicate
    expect( response ).toHavePathSatisfying( "data.users[1].role", role -> role == "admin" )

    // Path extraction
    expect( response ).path( "data.users[1].name" ).toBe( "Alice" )
    expect( response ).queryPath( "data.users[*].name" ).toInclude( "Bob" )
} )
```

## Class-Level `skip` Annotation

BDD test classes now support a class-level `skip` annotation, so an entire class can be skipped without touching each `describe()` or editing the runner's filters.

```js
/**
 * @skip
 */
component extends="testbox.system.BaseSpec" {

    function run(){
        describe( "Payment gateway", function(){
            // none of this runs while @skip is present
        } );
    }

}
```

Skipped classes are reported as skipped rather than silently omitted, so the count stays honest.

You can also pass a reason:

```js
/**
 * @skip Waiting on the sandbox credentials
 */
```

## MockBox `$args()` Improvements

`$args()` previously built its argument hash in a way that depended on struct iteration order. Two structurally identical structs built in a different order could hash differently, so a mock could fail to match arguments it should have matched and would return `null` instead.

This was always latent, but Lucee 7.1 changed its underlying map implementation and made it reproducible.

`$args()` now normalizes nested structures deterministically, so structurally-equal arguments match regardless of how they were built:

```js
var mock = createMock( "PaymentService" )
    .$( "charge" )
    .$args( { amount : 100, currency : "USD" } )
    .$results( true );

// matches, even though the keys were supplied in a different order
mock.charge( { currency : "USD", amount : 100 } );
```

`$args()` also now understands BoxLang `Set` and `Range` objects when matching.

## Summary

| Feature                                                          | Type        | Example                                                                             |
| ---------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------- |
| `withContext()`                                                  | Expectation | `expect( v ).withContext( "label" ).toBe( x )`                                      |
| `expectAny()`                                                    | Collection  | `expectAny( arr ).toBeGT( 2 )`                                                      |
| `expectSome()`                                                   | Collection  | `expectSome( arr, 2, 5 ).toBeGT( 2 )`                                               |
| `expectNone()`                                                   | Collection  | `expectNone( arr ).toBeEmpty()`                                                     |
| `assertAll()`                                                    | Grouped     | `assertAll( closures, "heading" )`                                                  |
| `toBeTruthy()`                                                   | Matcher     | `expect( v ).toBeTruthy()`                                                          |
| `toBeFalsy()`                                                    | Matcher     | `expect( v ).toBeFalsy()`                                                           |
| `toBeSameInstanceAs()`                                           | Matcher     | `expect( a ).toBeSameInstanceAs( b )`                                               |
| `toHaveSize()`                                                   | Matcher     | `expect( v ).toHaveSize( 3 )`                                                       |
| `toThrowMatching()`                                              | Matcher     | `expect( fn ).toThrowMatching( p )`                                                 |
| `toIncludeAll()`                                                 | Matcher     | `expect( v ).toIncludeAll( needles )`                                               |
| `toIncludeAny()`                                                 | Matcher     | `expect( v ).toIncludeAny( needles )`                                               |
| `toIncludeNone()`                                                | Matcher     | `expect( v ).toIncludeNone( needles )`                                              |
| `toBeASet()` / `nottoBeASet()`                                   | Set         | `expect( setOf( 1, 2 ) ).toBeASet()`                                                |
| `toEqualSet()` / `notToEqualSet()`                               | Set         | `expect( setOf( 1, 2 ) ).toEqualSet( setOf( 2, 1 ) )`                               |
| `toBeSubsetOf()` / `notToBeSubsetOf()`                           | Set         | `expect( setOf( 1 ) ).toBeSubsetOf( setOf( 1, 2 ) )`                                |
| `toBeSupersetOf()` / `notToBeSupersetOf()`                       | Set         | `expect( setOf( 1, 2 ) ).toBeSupersetOf( setOf( 1 ) )`                              |
| `toBeDisjointFrom()`                                             | Set         | `expect( setOf( 1 ) ).toBeDisjointFrom( setOf( 2 ) )`                               |
| `toHaveUnion()` / `notToHaveUnion()`                             | Set         | `expect( setOf( 1 ) ).toHaveUnion( setOf( 2 ), setOf( 1, 2 ) )`                     |
| `toHaveIntersection()` / `notToHaveIntersection()`               | Set         | `expect( setOf( 1, 2 ) ).toHaveIntersection( setOf( 2, 3 ), setOf( 2 ) )`           |
| `toHaveDifference()` / `notToHaveDifference()`                   | Set         | `expect( setOf( 1, 2 ) ).toHaveDifference( setOf( 2 ), setOf( 1 ) )`                |
| `toHaveSymmetricDifference()` / `notToHaveSymmetricDifference()` | Set         | `expect( setOf( 1, 2 ) ).toHaveSymmetricDifference( setOf( 2, 3 ), setOf( 1, 3 ) )` |
| `toBeRange()`                                                    | Range       | `expect( 1..10 ).toBeRange()`                                                       |
| `toContainValue()`                                               | Range       | `expect( 1..10 ).toContainValue( 5 )`                                               |
| `toContainRange()`                                               | Range       | `expect( 1..10 ).toContainRange( 2..5 )`                                            |
| `toBeInRange()`                                                  | Range       | `expect( 5 ).toBeInRange( 1..10 )`                                                  |
| `toBeBeforeRange()`                                              | Range       | `expect( 0 ).toBeBeforeRange( 1..10 )`                                              |
| `toBeAfterRange()`                                               | Range       | `expect( 11 ).toBeAfterRange( 1..10 )`                                              |
| `toBeBounded()`                                                  | Range       | `expect( 1..10 ).toBeBounded()`                                                     |
| `toBeUnbounded()`                                                | Range       | `expect( r ).toBeUnbounded()`                                                       |
| `toBeHalfBounded()`                                              | Range       | `expect( r ).toBeHalfBounded()`                                                     |
| `toBeIterable()`                                                 | Range       | `expect( 1..10 ).toBeIterable()`                                                    |
| `toBeAscending()`                                                | Range       | `expect( 1..10 ).toBeAscending()`                                                   |
| `toBeDescending()`                                               | Range       | `expect( 10..1 ).toBeDescending()`                                                  |
| `toHaveStep()`                                                   | Range       | `expect( r ).toHaveStep( 2 )`                                                       |
| `toClampTo()`                                                    | Range       | `expect( 1..10 ).toClampTo( 20, 10 )`                                               |
| `toHavePath()` / `notToHavePath()`                               | Navigator   | `expect( data ).toHavePath( "app.name" )`                                           |
| `toHavePathValue()` / `notToHavePathValue()`                     | Navigator   | `expect( data ).toHavePathValue( "app.name", "TestApp" )`                           |
| `toHavePathType()` / `notToHavePathType()`                       | Navigator   | `expect( data ).toHavePathType( "app.settings.port", "numeric" )`                   |
| `toHavePathSatisfying()` / `notToHavePathSatisfying()`           | Navigator   | `expect( data ).toHavePathSatisfying( "app.name", p -> p == "TestApp" )`            |
| `path()`                                                         | Navigator   | `expect( data ).path( "app.name" ).toBe( "TestApp" )`                               |
| `queryPath()`                                                    | Navigator   | `expect( data ).queryPath( "users[*].name" ).toInclude( "Alice" )`                  |

## Bug Fixes and Improvements

### Code Coverage Is Now Opt-In

The `coverageEnabled` URL parameter in the CFML test runner now defaults to `false` instead of `true`.

Code coverage requires [FusionReactor](https://www.fusion-reactor.com/), so defaulting it on meant every plain runner hit paid for a feature most runs did not want. If you rely on coverage, enable it explicitly:

```
/tests/runner.cfm?coverageEnabled=true
```

{% hint style="warning" %}
This is a behavioral change. If you were relying on the implicit default to collect coverage, you must now pass `coverageEnabled=true` or set it in your runner options.
{% endhint %}

### Date Equality In Assertions

Equalize assertions now compare date and date/time objects by their instant rather than calling `actual.equals()` blindly. Comparing a `java.util.Date` against a CFML date string, or two date objects of different concrete types, now behaves as expected instead of failing on type identity.

### Engine Detection

`isLucee()` returned `true` under BoxLang, because BoxLang registers a `lucee` server scope key for compatibility. Any spec branching or skipping on engine took the Lucee path when running on BoxLang. `isLucee()` now requires the absence of the `boxlang` key.

### Simple Reporter HTML Escaping

Bundle and spec names are now HTML-encoded in the Simple reporter, so a test name containing markup no longer breaks the report layout.

### Full Null Support

TestBox internals assumed a non-null runtime in several places, producing spurious null-reference errors on engines configured with full null support. Null handling was audited across the runners, coverage service and mock generator, and the configuration is now covered in CI.

### BoxLang CLI Runner

Several fixes land for the BoxLang CLI runner:

* The runner no longer misreads its own script path as a positional bundle argument.
* `KeyNotFoundException [url]` no longer crashes every CLI run on BoxLang 1.17 and later. The `url` scope is not registered in CLI mode, and the runner now params it rather than referencing it directly.
* `GetPageContextResponse()` no longer errors when running BoxLang in Adobe compatibility mode.


# What's New With 7.0.0

March 17, 2026

TestBox 7.x series continues our mission to be the best testing framework for BoxLang and CFML. This release is focused heavily on **BoxLang CLI runner enhancements**, real-time **streaming test execution via SSE**, a powerful **dry run** capability, the brand-new **TestBox RUN** web IDE, and significant quality-of-life improvements for developers working in both BoxLang and CFML environments.

![alt text](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/I9vg20v5wUFrzDZEb5Wh/image.png)

Finally, we have certified TestBox 7 for Lucee 7 and dropped support for Adobe 2021 to focus on modern engines and features.

## TestBox RUN — The BoxLang Test IDE

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b75a32f56aca939912a78a80d63affb60323d894%2Ftestbox-run.gif?alt=media)

**TestBox RUN** is a brand-new, BoxLang-native test runner and IDE shipped as part of TestBox 7. It is a fully-featured browser-based interface for discovering, running, and streaming your test results in real time — all powered by BoxLang and the new `StreamingRunner` SSE engine.

### What Is It?

TestBox RUN is a self-hosted single-page web app (`bx/tests/index.bxm`) that you drop into your BoxLang project and open in your browser. It communicates with your existing `runner.bxm` endpoint and streams spec results as they complete via **Server-Sent Events**. No build toolchain, no external service — just BoxLang.

### Feature Highlights

#### Real-Time Streaming Test Tree

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-063893771ff35546d7f38889fb7f03e80a354eb8%2Ftestbox-suite-run.gif?alt=media)

Results appear in the UI as each spec finishes. The test tree updates live — passing specs turn green, failures turn red, and errors surface immediately with their full message — long before the suite finishes.

#### Beautiful, Responsive UI

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-4eedb6dcfd39699681493052ec69a13e7ce56c84%2Ftestbox-run-help.png?alt=media) ![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-59873e9fdb6a57fb2d0ebdf0b128173f735a7e4d%2Ftestbox-run-light.png?alt=media)

* **Dark / Light theme toggle** with preference persistence in `localStorage`
* **Keyboard-first UX** with a full set of shortcuts:

| Shortcut         | Action                             |
| ---------------- | ---------------------------------- |
| `⌘/Ctrl + K`     | Focus the search bar               |
| `Esc`            | Clear search                       |
| `⌘/Ctrl + Enter` | Run all tests                      |
| `⌘/Ctrl + .`     | Reload / rediscover tests          |
| `⌘/Ctrl + ,`     | Open Settings                      |
| `⌘/Ctrl + B`     | Toggle expand/collapse all bundles |
| `⌘/Ctrl + D`     | Toggle dark/light mode             |
| `⌘/Ctrl + H`     | Open the About / Help dialog       |

#### Live Search & Filtering

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-50efe216a8008d5b8a6592dfab05c1ab1cdae799%2Ftestbox-run-search.gif?alt=media)

A **search bar** at the top lets you instantly filter the test tree by bundle, suite, or spec name. Combined with the **status filter chips** (Passed / Failed / Errored / Skipped), you can zero in on exactly the tests you care about.

#### Per-Bundle Run & Summary Strip

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-8607eb107ab46ae58328b23abea5c2d56f975d54%2Ftestbox-run-bundle-run.gif?alt=media)

Each bundle card has its own **▶ Run** button so you can re-run a single bundle without re-running the entire suite. A compact **results strip** beneath each bundle header shows pass/fail/error/skipped counts and total duration at a glance.

#### Debug Buffer Panel

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-833a28e71ef3a1826d042828c03fb4fb9cdc73ee%2Ftestbox-run-debug-buffer.gif?alt=media)

Any output captured in the TestBox debug buffer during a run is surfaced in a collapsible per-bundle **Debug Panel**, accessible via a bug icon on the bundle strip. Each entry is rendered with its label and a formatted data view.

#### Floating Progress Widget

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0adef9b1ce1ebd0f65458b348f85fa9930a86abb%2Ftestbox-run-progress-bar.gif?alt=media)

A floating progress widget appears during active runs, showing:

* Current bundle running
* Specs completed vs. total
* Animated progress bar with percentage

#### Configurable Settings

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-036f5558d839074e0e45bf48a3eed0c3508bc3ea%2Ftestbox-run-settings.gif?alt=media)

Click the gear icon (or `⌘/Ctrl + ,`) to open the **Settings modal**, where you can configure:

* Runner URL (relative path or absolute HTTP/S)
* Directory and bundles pattern
* Recurse toggle
* Labels and excludes

All settings are saved in `localStorage` and applied on the next visit. Every setting can also be overridden via URL query parameters for quick CI integration:

```
/tests/?directory=tests.specs.integration&labels=slow&runnerUrl=/tests/runner.bxm
```

### Getting Started with TestBox RUN

TestBox RUN is included automatically with every TestBox 7 installation under `bx/tests/`. Point your web server at `bx/tests/index.bxm` and open it in your browser.

Every ColdBox application generated with our `ColdBox CLI` will also include TestBox RUN out of the box.

You can also generate a new test harness with TestBox RUN support using the `testbox generate` command:

```bash
testbox generate harness --help
```

{% hint style="info" %}
TestBox RUN requires a running web server and a `runner.bxm` (or `runner.bx`) endpoint that supports the SSE streaming protocol. If you are building a pure CLI application, use the [BoxLang CLI runner](https://github.com/ortus-docs/testbox-docs/blob/v7.x/getting-started/running-tests/boxlang-runner.md) with `--stream` instead.
{% endhint %}

### Coming Soon: TestBox RUN Desktop App

{% hint style="success" %}
**Exciting news for BoxLang Desktop Runtime fans!**

We are actively working on a **native desktop application** version of TestBox RUN, built entirely on the **BoxLang Desktop Runtime**. The desktop app will connect to any web-accessible runner URL — local or remote — and provide the same beautiful real-time streaming UI without a browser. Stay tuned at [testbox.run](https://www.testbox.run) for announcements, early access, and previews.
{% endhint %}

## Engine Support

Adobe 2021 has been dropped and Lucee 7 is now fully supported and certified.

| Engine       | Supported    |
| ------------ | ------------ |
| BoxLang 1.x+ | ✅ PREFERRED  |
| Lucee 5.x    | ✅ DEPRECATED |
| Lucee 6.x    | ✅            |
| Lucee 7.x    | ✅ NEW        |
| Adobe 2023   | ✅ DEPRECATED |
| Adobe 2025   | ✅            |
| Adobe 2021   | ❌ Dropped    |

{% hint style="warning" %}
Adobe 2021 is no longer supported as of TestBox 7. Please upgrade to Adobe 2023+ or migrate to [BoxLang](https://boxlang.io/).
{% endhint %}

## TestBox RUN

## Dry Run & Spec Discovery

Two long-requested features have finally landed: the ability to **discover** which specs will run without executing them, and a full **dry run** mode. These are invaluable for large test suites where you need to audit coverage or validate filtering before committing to a full run.

Call the `dryRun()` method on your TestBox instance to execute the full discovery and filtering pipeline and get a complete report of what **would have** run — without actually invoking any spec closures.

```javascript
var tb      = new testbox.system.TestBox( bundles = "tests.specs" );
var results = tb.dryRun();
```

The BoxLang CLI runner also gains a `--dry-run` flag that performs the same discovery and filtering process, outputting a structured report of all suites and specs that would have been executed:

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-88da83c3344691bf9344a6868f0b908947734970%2Ftestbox-boxlang-dryrun.gif?alt=media)

```bash
./testbox/run --dry-run
```

The output lists every suite and spec that would be executed, along with their labels and any skip reasons — perfect for CI pipeline auditing and test inventory reporting.

### Dry Run JSON Output

Pass `--dry-run=json` to receive the full discovery payload as raw JSON instead of the formatted text output. This is ideal for programmatic consumption — CI tools, custom reporters, or any external script that needs to process the test inventory:

```bash
./testbox/run --dry-run=json
./testbox/run --dry-run=json --bundles=tests.specs.MySpec | jq .
```

{% hint style="success" %}
Dry run mode respects all the same filtering options as a normal run: `--labels`, `--bundles`, `--directory`, `--testSuites`, `--testSpecs`, etc.
{% endhint %}

## Streaming Runner & Real-Time Output (TESTBOX-441, TESTBOX-442)

TestBox 7 introduces a brand-new **StreamingRunner** that pushes test results to the client as they complete via **Server-Sent Events (SSE)**. This means you no longer have to wait for the entire suite to finish before seeing results — each spec result is streamed in real time. This of course, requires an SSE-capable client, but it opens up powerful new workflows for CI pipelines and large test suites where immediate feedback is crucial.

### StreamingRunner

The new `StreamingRunner.cfc` is available under `testbox.system.runners.StreamingRunner` and can be used programmatically or wired into any SSE-capable endpoint.

```javascript
component {
    function streamTests( event, rc, prc ) {
        event.setHTTPHeader( name="Content-Type", value="text/event-stream" );
        event.setHTTPHeader( name="Cache-Control", value="no-cache" );

        new testbox.system.runners.StreamingRunner(
            bundles  = "tests.specs",
            options  = {},
            reporter = "text"
        ).run();
    }
}
```

### BoxLang CLI `--stream` Flag

The BoxLang CLI runner gains a `--stream` flag that activates real-time output of test results as they execute rather than buffering until completion:

```bash
./testbox/run --stream
./testbox/run --directory=tests.specs --stream
```

{% hint style="info" %}
Streaming output is especially useful in CI environments where you want live progress rather than waiting for the full suite to complete before seeing any output.
{% endhint %}

## BoxLang Runner Enhancements

The BoxLang CLI runner has received a significant set of new options that give you fine-grained control over output, failure reporting, and performance analysis.

### `--show-failed-only` (TESTBOX-444)

Focus your terminal output exclusively on failures and errors, suppressing all passing and skipped specs:

```bash
./testbox/run --show-failed-only
```

### `--stacktrace` Control (TESTBOX-445)

Choose how much stack trace detail is shown for failures and exceptions. The default is `short` to keep output readable:

```bash
./testbox/run --stacktrace=short   # default: condensed first frame
./testbox/run --stacktrace=full    # complete Java/BoxLang stack trace
```

### Output & Performance Options (TESTBOX-446)

A full suite of output-control and performance-analysis flags are now available:

```bash
# Show or hide passing specs (default: true)
./testbox/run --show-passed=false

# Show or hide skipped specs (default: true)
./testbox/run --show-skipped=false

# Abort the run after N failures
./testbox/run --max-failures=10

# Flag any spec that takes longer than N milliseconds as slow
./testbox/run --slow-threshold-ms=500

# Print a summary of the N slowest specs at the end of the run
./testbox/run --top-slowest=5
```

Combining these gives you a clean, focused workflow:

```bash
./testbox/run --show-failed-only --stacktrace=short --max-failures=5 --top-slowest=3
```

### Application Mappings Auto-Load (TESTBOX-440)

The BoxLang runner now **automatically attempts to load `Application.bx` mappings** from your project root before executing tests. This means any custom path mappings, datasources, or settings defined in your `Application.bx` are available to your specs without any extra configuration.

{% hint style="success" %}
This brings the BoxLang CLI runner experience much closer to running tests in a full web server environment, reducing the friction of maintaining separate CLI-specific configuration.
{% endhint %}

## New `ConsoleUtil` Toolkit (TESTBOX-443)

A new `ConsoleUtil` class has been added to `testbox.system.util.ConsoleUtil` to provide a rich set of helpers for building beautiful CLI tooling on top of TestBox. It includes support for:

* **ANSI color and style** output helpers
* **Bordered and padded boxes** for drawing section headers
* **Progress indicators** and spinner helpers
* **Table rendering** for structured output
* **Symbols and icons** normalized across platforms

```javascript
var console = new testbox.system.util.ConsoleUtil();

console.printLine( console.green( "All tests passed!" ) );
console.printBox( "Suite: My Application Tests", style="double" );
console.printKeyValue( "Total Specs", 142 );
console.printKeyValue( "Failures",    0,  color="green" );
```

## `ConsoleReporter` — Hide Skipped Tests (TESTBOX-433)

The `ConsoleReporter` now accepts a `hideSkipped` option (default `false`) so you can suppress skipped spec output for cleaner terminal readability when you have many pending specs:

```javascript
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type        : "testbox.system.reports.ConsoleReporter",
        options     : { hideSkipped : true }
    }
);
```

From the BoxLang CLI runner, use `--show-skipped=false` (see above).

## Suite Filtering Improvements (TESTBOX-435)

TestBox now performs **direct suite name matching** when the `testSuites` filter is active. Previously, nested suites could be skipped even when they exactly matched the filter value. Now, if a suite's name is a direct match for the filter, it will always be included regardless of nesting depth.

This makes granular suite targeting far more reliable from all runners:

```bash
# Via CLI runner
./testbox/run --testSuites="My Integration Suite"

# Via TestBox directly
new testbox.system.TestBox(
    bundles    = "tests.specs",
    testSuites = "My Integration Suite"
).run();
```

## TestBox CLI Updates

![alt text](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-09a293802e5499103cae1167b3acb6b832ddd161%2Ftestbox-cli-info.png?alt=media)

The `testbox-cli` CommandBox module has received a major update in version **1.8.0** to align with TestBox 7.

### New Commands

#### `testbox info`

A new `testbox info` command displays detailed information about the current TestBox installation, including the installed version, installation path, and key configuration detected in your project:

```bash
testbox info
```

#### `testbox reinstall`

A new `testbox reinstall` command forces a clean reinstallation of the TestBox CLI package itself — useful when you suspect your current installation is corrupted or outdated:

```bash
testbox reinstall
```

{% hint style="info" %}
This command reinstalls the `testbox-cli` CommandBox module only, not the TestBox library itself. To reinstall the TestBox library, use `box install testbox --force`.
{% endhint %}

### Streaming Results via `testbox run --streaming`

The `testbox run` command now supports a `--streaming` flag that taps into the new `StreamingRunner` to deliver real-time test results to your terminal as each spec completes rather than buffering until the entire suite finishes:

```bash
testbox run --streaming
```

Pair it with `--verbose` to include all passing specs in the live output — by default only failures and skipped specs are persisted:

```bash
testbox run --streaming --verbose
```

{% hint style="info" %}
Streaming output is ideal for CI environments where you want immediate feedback on test progress rather than waiting for the full suite to complete before seeing any results. It works best with BoxLang, but can be used with CFML engines that support SSE as well.
{% endhint %}

### TestBox RUN Integration

The CLI now ships with support for the new **TestBox RUN** runner for BoxLang, enabling native SSE-based streaming runs directly from the CommandBox CLI without needing a separate web server.

### Template Updates

Both CFML and BoxLang generation templates have been refreshed to reflect the latest TestBox 7 conventions and best practices.

### Bug Fixes

* `getTestBoxDescriptor()` argument was previously ignored and is now correctly applied.
* The `testbox` package is now used as the single source of truth for version and descriptor resolution rather than duplicating logic across the CLI module, preventing potential drift.

### Improved Help Messages

All commands have received updated help text with clearer descriptions, usage examples, and argument documentation.

## Release Notes

### Bugs

| #                                                                      | Title                                                                                                    |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| [TESTBOX-432](https://ortussolutions.atlassian.net/browse/TESTBOX-432) | `toBeWithCase` needs the `caseSensitive` flag set                                                        |
| [TESTBOX-436](https://ortussolutions.atlassian.net/browse/TESTBOX-436) | Trim is killing leading ANSI escapes by removing `chr(27)` in the console reporter                       |
| [TESTBOX-437](https://ortussolutions.atlassian.net/browse/TESTBOX-437) | Update location detection of TestBox library on Windows for `BoxLangRunner.bx`                           |
| [TESTBOX-438](https://ortussolutions.atlassian.net/browse/TESTBOX-438) | CLI args not being passed to runner on Windows using BoxLang                                             |
| [TESTBOX-439](https://ortussolutions.atlassian.net/browse/TESTBOX-439) | Fix TestBox scanning from the root if directory was not passed but bundles were using the BoxLang Runner |

### Improvements

| #                                                                      | Title                                                                                                                           |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| [TESTBOX-430](https://ortussolutions.atlassian.net/browse/TESTBOX-430) | BoxLang PRIME updates for detecting CGI scopes when doing CLI testing instead of web                                            |
| [TESTBOX-434](https://ortussolutions.atlassian.net/browse/TESTBOX-434) | Improve static block usage on BoxLang runner                                                                                    |
| [TESTBOX-435](https://ortussolutions.atlassian.net/browse/TESTBOX-435) | Determine if a suite is a DIRECT match for the `testSuites` filter; if so, run it — allows reliable suite filtering via runners |
| [TESTBOX-440](https://ortussolutions.atlassian.net/browse/TESTBOX-440) | Attempt to load `Application` mappings using the BoxLangRunner                                                                  |

### New Features

| #                                                                      | Title                                                                                                                   |
| ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| [TESTBOX-213](https://ortussolutions.atlassian.net/browse/TESTBOX-213) | Allow retrieving specs that will be run                                                                                 |
| [TESTBOX-324](https://ortussolutions.atlassian.net/browse/TESTBOX-324) | Enable a "Dry Run" so you can get a list of tests without actually running them                                         |
| [TESTBOX-431](https://ortussolutions.atlassian.net/browse/TESTBOX-431) | Lucee 7 certification                                                                                                   |
| [TESTBOX-433](https://ortussolutions.atlassian.net/browse/TESTBOX-433) | `ConsoleReporter` option `hideSkipped` to omit skipped tests from output                                                |
| [TESTBOX-441](https://ortussolutions.atlassian.net/browse/TESTBOX-441) | New `StreamingRunner` to provide execution streaming of tests via SSE                                                   |
| [TESTBOX-442](https://ortussolutions.atlassian.net/browse/TESTBOX-442) | New `--stream` option for the BoxLang runner to stream results and tests in real-time                                   |
| [TESTBOX-443](https://ortussolutions.atlassian.net/browse/TESTBOX-443) | New `ConsoleUtil` for building beautiful CLI tooling                                                                    |
| [TESTBOX-444](https://ortussolutions.atlassian.net/browse/TESTBOX-444) | New `--show-failed-only` option for the BoxLang Runner                                                                  |
| [TESTBOX-445](https://ortussolutions.atlassian.net/browse/TESTBOX-445) | New `--stacktrace=short\|full` option for the BoxLang runner                                                            |
| [TESTBOX-446](https://ortussolutions.atlassian.net/browse/TESTBOX-446) | New BoxLang runner options: `--show-passed`, `--show-skipped`, `--max-failures`, `--slow-threshold-ms`, `--top-slowest` |

### Tasks

| #                                                                      | Title                   |
| ---------------------------------------------------------------------- | ----------------------- |
| [TESTBOX-447](https://ortussolutions.atlassian.net/browse/TESTBOX-447) | Drop Adobe 2021 support |


# About This Book

Learn about the authors of TestBox and how to support the project.

The source code for this book is hosted on GitHub: <https://github.com/Ortus-Solutions/testbox-docs>. You can freely contribute to it and submit pull requests. The contents of this book is copyrighted by [Ortus Solutions, Corp](http://www.ortussolutions.com) and cannot be altered or reproduced without the author's consent. All content is provided *"As-Is"* and can be freely distributed.

## External Trademarks & Copyrights

Flash, Flex, ColdFusion, and Adobe are registered trademarks and copyrights of Adobe Systems, Inc.

BoxLang, ColdBox, CommandBox, FORGEBOX, TestBox, ContentBox, and Ortus Solutions are all trademarks and copyrights of Ortus Solutions, Corp.

## Notice of Liability

The information in this book is distributed “as is” without warranty. The author and Ortus Solutions, Corp shall not have any liability to any person or entity concerning loss or damage caused or alleged to be caused directly or indirectly by the content of this training book, software, and resources described in it.

## Contributing

We highly encourage contributions to this book and our open-source software. The source code for this book can be found in our [GitHub repository](https://github.com/Ortus-Solutions/testbox-docs) where you can submit pull requests.

## Charitable Proceeds

15% of the proceeds of this book will go to charity to support orphaned kids in El Salvador - <http://www.harvesting.org/>. So please donate and purchase the printed version of this book; every book sold can help a child for almost 2 months.

### Shalom Children's Home

![Shalom Children's Home](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/YGmE677xDyN04SbuPhXM/shalom.jpg)

Shalom Children’s Home (<https://www.harvesting.org/>) is one of the ministries that are dear to our hearts located in El Salvador. During the 12-year civil war that ended in 1990, many children were left orphaned or abandoned by parents who fled El Salvador. The Benners saw the need to help these children and received 13 children in 1982. Little by little, more children came on their own, churches and the government brought children to them for care, and the Shalom Children’s Home was founded.

Shalom now cares for over 80 children in El Salvador, from newborns to 18 years old. They receive shelter, clothing, food, medical care, education, and life skills training in a Christian environment. The home is supported by a child sponsorship program.

We have personally supported Shalom for over 6 years now; it is a place of blessing for many children in El Salvador who either has no families or have been abandoned. This is a good earth to seed and plant.


# Author

## Luis Fernando Majano Lainez

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/MXL3teZWiriT9MKu52fr/luismajano.jpg)

Luis Majano is a Computer Engineer with over 16 years of software development and systems architecture experience. He was born in [San Salvador, El Salvador](http://en.wikipedia.org/wiki/El_Salvador) in the late 70’s, during a period of economical instability and civil war. He lived in El Salvador until 1995 and then moved to Miami, Florida where he completed his Bachelors of Science in Computer Engineering at [Florida International University](http://fiu.edu). Luis resides in The Woodlands, Texas with his beautiful wife Veronica, baby girl Alexia and baby boy Lucas!

He is the CEO of [Ortus Solutions](http://www.ortussolutions.com), a consulting firm specializing in web development, ColdFusion (CFML), Java development and all open source professional services under the ColdBox and ContentBox stack. He is the creator of ColdBox, ContentBox, WireBox, MockBox, LogBox and anything “BOX”, and contributes to many open source ColdFusion projects. He is also the Adobe ColdFusion user group manager for the [Inland Empire](http://www.iecfug.org). You can read his blog at [www.luismajano.com](http://www.luismajano.com)

Luis has a passion for Jesus, tennis, golf, volleyball and anything electronic. Random Author Facts:

* He played volleyball in the Salvadorean National Team at the tender age of 17
* The Lord of the Rings and The Hobbit is something he reads every 5 years. (Geek!)
* His first ever computer was a Texas Instrument TI-86 that his parents gave him in 1986. After some time digesting his very first BASIC book, he had written his own tic-tac-toe game at the age of 9. (Extra geek!)
* He has a geek love for circuits, microcontrollers and overall embedded systems.
* He has of late (during old age) become a fan of running and bike riding with his family.

> Keep Jesus number one in your life and in your heart. I did and it changed my life from desolation, defeat and failure to an abundant life full of love, thankfulness, joy and overwhelming peace. As this world breathes failure and fear upon any life, Jesus brings power, love and a sound mind to everybody!
>
> “Trust in the LORD with all your heart, and do not lean on your own understanding.”\
> Proverbs 3:5

## Contributors

### Jorge Emilio Reyes Bendeck

Jorge is an Industrial and Systems Engineer born in El Salvador. After finishing his Bachelor studies at the Monterrey Institute of Technology and Higher Education [ITESM](http://www.itesm.mx/wps/wcm/connect/ITESM/Tecnologico+de+Monterrey/English), Mexico, he went back to his home country where he worked as the COO of[ Industrias Bendek S.A.](http://www.si-ham.com/). In 2012 he left El Salvador and moved to Switzerland in persuit of the love of his life. He married her and today he resides in Basel with his lovely wife Marta and their daughter Sofía.

Jorge started working as project manager and business developer at Ortus Solutions, Corp. in 2013, . At Ortus he fell in love with software development and now enjoys taking part on software development projects and software documentation! He is a fellow Cristian who loves to play the guitar, worship and rejoice in the Lord!

> Therefore, if anyone is in Christ, the new creation has come: The old has gone, the new is here!\
> 2 Corinthians 5:17


# Overview

A quick overview of TestBox

**TestBox** is a next-generation testing framework for the [BoxLang](https://www.boxlang.io) JVM language and ColdFusion (CFML) language based on [BDD](http://en.wikipedia.org/wiki/Behavior-driven_development) (Behavior Driven Development) for providing a clean, obvious syntax for writing tests. It contains not only a testing framework, console/web runner, assertions, and expectations library but also ships with several mocking utilities.

### Styles

In TestBox you can write your tests in two different styles or approaches.

#### BDD (Behavior Driven Development)

BDD stands for **behavior-driven development** and is highly based on creating specifications and expectations of results in a readable DSL (Domain Specific Language). You are not focusing on a specific unit and method to test, but on functionality, features and more. This can encompass not only unit but also integration testing. You have several methods that you can use in order to denote functionality and specifications:

* `describe()`
* `feature()`
* `story()`
* `given(), when(), then()`
* `it() or test()`

```cfscript
describe( "My calculator features", () => {
	
	beforeEach( () => {
		variables.calc = new Calculator()
	} )
		
	// Using expectations library
	it( "can add", () => {
		expect( calc.add(1,1) ).toBe( 2 )
	} )
	
	// Using assert library
	test( "it can multiply", () => {
		$assert.isEqual( calc.multiply(2,2), 4 )
	} )
} )
```

#### xUnit (Test Driven Development)

xUnit style of testing is the more traditional TDD or **test-driven development** approach where you create a test case bundle class that matches the software under test, and for each method in the SUT, you create a test method in the test bundle class.

```java
@DisplayName "My calculator features"
class{

	property calc;
	
	function setup(){
		calc = new Calculator()
	}
	
	// Function name includes the word 'test'
	// Using expectations library
	function testAdd(){
		expect( calc.add(1,1) ).toBe( 2 )
	}
		
	// Any name, but with a test annotation
	// Using assertions library
	@DisplayName "It can multiply two operands"
	@test
	function itCanMultiply(){
		$assert.isEqual( calc.multiply(2,2), 4 )
	}
}
```

### Assertions & Expectations

We also give you two ways to do assertions:

1. [Assertions](/getting-started/testbox-xunit-primer/assertions) library, which is a traditional approach to assertions
2. [Expectations](/digging-deeper/expectations) library, which is a more fluent approach to assertions.

```cfscript
// Assertions
assert( expression, "custom message" )

// Expectations
expect( structKeyExists( handler, "mixinTest" ) ).toBeTrue();
expect( structKeyExists( handler, "repeatThis" ) ).toBeTrue();
expect( structKeyExists( handler, "add" ) ).toBeTrue();
expect( target.$callLog().relocate[ 1 ].url ).toInclude( "dashboard" );
```

### Life-Cycles

Both approaches also offer different [life-cycle](/digging-deeper/life-cycle-methods) callbacks so you can execute code during different times in the test execution.

{% tabs %}
{% tab title="BDD" %}

```cfscript
beforeEach( function( currentSpec ){
    setup();
    target = prepareMock( getInstance( "coldbox.system.FrameworkSupertype" ) );
} );

afterEach( function( currentSpec ){
    getCache( "template" ).clearAll();
    variables.scheduler.shutdown();
} );


function beforeAll() {
	super.beforeAll();
	
	// Login User
	variables.loggedInData = loginUser();
	
	variables.loggedInUserId = variables.loggedInData.user.getUserId();
	
	variables.testTimeOffEmployeeId = qb
		.select( "FK_userId" )
		.from( "timeOff" )
		.where( "requestType", "vacation" )
		.first()
		.FK_userId;
}

function afterAll() {
	variables.userService.clearCaches()
}
```

{% endtab %}

{% tab title="xUnit" %}

```cfscript
function setup() {
	super.setup();

	if ( !isNull( request.testUserData ) ) {
		getRequestContext().setValue( "x-auth-token", request.testUserData.token.access_token );
	}

	return;
}

function tearDown(){
	request.clear()
}

function beforeTests() {
	
	// Login User
	variables.loggedInData = loginUser();
	
	variables.loggedInUserId = variables.loggedInData.user.getUserId();
	
	variables.testTimeOffEmployeeId = qb
		.select( "FK_userId" )
		.from( "timeOff" )
		.where( "requestType", "vacation" )
		.first()
		.FK_userId;
}

function afterTests() {
	variables.userService.clearCaches()
}
```

{% endtab %}
{% endtabs %}

### Utilities

TestBox will also offer different utilities:

* Debug output to a debug buffer
* Mock classes, methods and properties
* Extension data mocking and JSON mocking
* Logging facilities

### Runners

You can also execute your tests via the CLI, IDE or the web server.

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/WMA272ff6xpyIdaPpIS1/testbox-text-reporter.png" alt=""><figcaption></figcaption></figure>

### Reports

TestBox can produce many different types of reports for your test executions:

* CLI / Console Output
* VSCode Output
* JSON
* XML
* JUNIT
* TAP
* HTML
* DOC
* Your own

Here is a few samples:

{% tabs %}
{% tab title="BDD - BoxLang" %}

```java
class{

  function run(){
  	describe( "My calculator features", () => {
	
		beforeEach( () => {
			variables.calc = new Calculator()
		} )
			
		// Using expectations library
		it( "can add", () => {
			expect( calc.add(1,1) ).toBe( 2 )
		} )
		
		// Using assert library
		test( "it can multiply", () => {
			$assert.isEqual( calc.multiply(2,2), 4 )
		} )
	} )
  }

}
```

{% endtab %}

{% tab title="xUnit - BoxLang" %}

```java
/**
 * My calculator features
 */
class{

	property calc;
	
	function setup(){
		calc = new Calculator()
	}
	
	// Function name includes the word 'test'
	// Using expectations library
	function testAdd(){
		expect( calc.add(1,1) ).toBe( 2 )
	}
		
	// Any name, but with a test annotation
	// Using assertions library
	@test
	function itCanMultiply(){
		$assert.isEqual( calc.multiply(2,2), 4 )
	}
}
```

{% endtab %}

{% tab title="BDD - CFML" %}

```cfscript
component{

  function run(){
  	describe( "My calculator features", () => {
	
		beforeEach( () => {
			variables.calc = new Calculator()
		} );
			
		// Using expectations library
		it( "can add", () => {
			expect( calc.add(1,1) ).toBe( 2 )
		} );
		
		// Using assert library
		test( "it can multiply", () => {
			$assert.isEqual( calc.multiply(2,2), 4 )
		} );
	} );
  }

}
```

{% endtab %}

{% tab title="xUnit - CFML" %}

```cfscript
/**
 * My calculator features
 */
component{
	
	property calc;
	
	function setup(){
		calc = new Calculator()
	}
	
	// Function name includes the word 'test'
	// Using expectations library
	function testAdd(){
		expect( calc.add(1,1) ).toBe( 2 )
	}
		
	// Any name, but with a test annotation
	// Using assertions library
	function itCanMultiply() test{
		$assert.isEqual( calc.multiply(2,2), 4 )
	}
}
```

{% endtab %}
{% endtabs %}

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/puqaoAxY8ArDEwwThxqN/image.png" alt=""><figcaption><p>Runner</p></figcaption></figure>

## Useful Resources

* [Approaches to Mocking](http://www.onjava.com/pub/a/onjava/2004/02/11/mocks.html)
* [Wikipedia Mock Objects](http://en.wikipedia.org/wiki/Mock_object)
* [Using mock objects for complex unit tests IBM developerWorks](http://www-128.ibm.com/developerworks/rational/library/oct06/pollice/index.html)
* [Unit testing with mock objects IBM developerWorks](http://www.ibm.com/developerworks/library/j-mocktest.html)
* [Emergent Design by Scott Bain](http://www.netobjectives.com/emergent-design-evolutionary-nature-professional-software-development)
* [Mocks Aren't Stubs by Martin Fowler](http://martinfowler.com/articles/mocksArentStubs.html)


# Installation

Get up and running quickly

## Framework

TestBox can be installed via [CommandBox CLI](https://www.ortussolutions.com/products/commandbox) as a development dependency in the root of your projects:

```bash
// Create a new project
mkdir myProject --cd

// latest stable version
box install testbox --saveDev

// latest bleeding edge
box install testbox@be --saveDev
```

{% hint style="info" %}
Please note the `--saveDev` flag, which tells CommandBox that TestBox is a development dependency and not a production dependency.
{% endhint %}

{% hint style="danger" %}
DO NOT USE TESTBOX IN PRODUCTION.
{% endhint %}

The only requirement is that it be in either in the webroot or in a location where you create a `/testbox` mapping to it's folder.

### System Requirements

| Engine                                                                                                                                             | Support                             |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| <img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/nBKlC8tRsSQv1VO6Wgge/image.png" alt="" data-size="line"> **BoxLang 1.x+** | ✅ **Preferred**                     |
| Lucee 6.x                                                                                                                                          | ✅ Supported                         |
| Lucee 7.x                                                                                                                                          | ✅ Supported (new in 7.0)            |
| Adobe ColdFusion 2023                                                                                                                              | ✅ Supported (deprecated)            |
| Adobe ColdFusion 2025                                                                                                                              | ✅ Supported                         |
| Lucee 5.x                                                                                                                                          | ⚠️ Deprecated — upgrade recommended |
| Adobe ColdFusion 2021                                                                                                                              | ❌ Dropped as of TestBox 7           |

{% hint style="success" %}
TestBox is designed first and foremost for [BoxLang](https://boxlang.io) and remains fully compatible with modern CFML engines.
{% endhint %}

{% hint style="warning" %}
Adobe ColdFusion 2021 support has been **dropped** as of TestBox 7. Please upgrade to Adobe 2023+ or migrate to [BoxLang](https://boxlang.io).
{% endhint %}

### What's Included

Here is a table of what's included in the installation package which goes in `/{project}/testbox`

<table><thead><tr><th width="206">Folder</th><th>Description</th></tr></thead><tbody><tr><td><strong>bx</strong></td><td>BoxLang tools</td></tr><tr><td><strong>cfml</strong></td><td>CFML Tools</td></tr><tr><td><strong>system</strong></td><td>The main system framework folder</td></tr><tr><td><strong>test-visualizer</strong></td><td>A static visualizer of JSON reports. Just drop in a <code>test-results.json</code> and run it!</td></tr><tr><td><strong>tests</strong></td><td>Several sample tests and runners are actually used to build TestBox</td></tr></tbody></table>

#### <img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/nBKlC8tRsSQv1VO6Wgge/image.png" alt="" data-size="line"> BoxLang Tools

In the `bx` folder you will find specific BoxLang tools:

<table><thead><tr><th width="166">Folder</th><th>Description</th></tr></thead><tbody><tr><td><strong>browser</strong></td><td>This is a little utility to facilitate navigating big testing suites. This helps navigate to the suites you want and execute them instead of typing all the time.</td></tr><tr><td><strong>tests</strong></td><td>A vanilla test runner for any application</td></tr><tr><td><strong>runner</strong></td><td>A simple GUI test runner</td></tr></tbody></table>

#### CFML Tools

In the `cfml` folder you will find specific BoxLang tools:

<table><thead><tr><th width="165">Folder</th><th>Description</th></tr></thead><tbody><tr><td><strong>browser</strong></td><td>This is a little utility to facilitate navigating big testing suites. This helps navigate to the suites you want and execute them instead of typing all the time.</td></tr><tr><td><strong>tests</strong></td><td>A vanilla test runner for any application</td></tr><tr><td><strong>runner</strong></td><td>A simple GUI test runner</td></tr></tbody></table>

### IDE Tooling

Now that you are installed, please set up your favorite IDE with our tooling extensions so it can make your testing experience more enjoyable.

{% content-ref url="/pages/-LA-UitUq9HzppVNby5A" %}
[IDE Tools](/getting-started/installing-testbox/ide-tools)
{% endcontent-ref %}

## TestBox CLI

TestBox comes with its own CLI for CommandBox. You can use it to generate tests, harnesses, and suites and also run executions from the CLI.

```bash
install testbox-cli
```

You will now have the `testbox` namesapce available to you, try it out

```bash
testbox help
```

### Generating a Testing Harness

Once you install TestBox, you'll need a quick way to set up a testing harness in your project. The `generate harness` command will add a new `/tests` folder to your application with a few example tests to get you started.

```bash
testbox generate harness
```

`/tests` - The test harness generated

* `/resources` - Where you can place any kind of testing helpers, data, etc
* `/specs` - Where your test bundles can go
  * `/unit`
  * `/integration`
* `Application.bx|cfc` - Your test harness applilcation file. Controls life-cycle and application concerns.
* `runner.bx|cfm` - A web runner template that executes ALL your tests with tons of different options from a running web server.
* `test.xml` - An ANT task to do JUNIT testing.

You can then run your tests by executing the `testbox run` command in CommandBox or by visiting the web runner in the generated harness: `http://localhost/tests/runner.cfm`

```bash
testbox run --help
```

### Generating Tests

You can also use the CLI to generate tests according to your style and also it detects if you are using BoxLang or a CFML engine.

```bash
testbox create bdd --help
testbox create unit --help
```

### Language Generation

If you want to be explicit you can use the `language` id to set it to your preferred language for generation and usage. We recommend this so all CLI tooling can detect what language your project is in.

```bash
# For BoxLang Generation
package set language="boxlang"

# For CFML
package set language="cfml"
```


# IDE Tools

A modern editor can enhance your testing experience. We maintain editor integrations that help you write, navigate, and run TestBox tests.

## VSCode Plugin

The VSCode plugin is the best way for you to interact with TestBox alongside the BoxLang plugin. It allows you to run tests, generate tests, navigate tests and much more.

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/UforLm5nKgp2rin0Sias/image.png" alt=""><figcaption></figcaption></figure>

{% embed url="<https://marketplace.visualstudio.com/items?itemName=ortus-solutions.vscode-boxlang>" %}
BoxLang
{% endembed %}

{% embed url="<https://marketplace.visualstudio.com/items?itemName=ortus-solutions.vscode-testbox>" %}
TestBox
{% endembed %}

## Sublime Text Package

The [BoxLang Sublime Text package](https://boxlang.ortusbooks.com/getting-started/ide-tooling/boxlang-sublime-text) adds BoxLang syntax highlighting, completions, inline documentation, and a native TestBox runner to Sublime Text 4.

Install **BoxLang** through Package Control. With TestBox 7 or later available in your project, use the Command Palette to run the current bundle, the spec or suite at the cursor, all tests, or repeat the last run. The package uses the BoxLang CLI runner by default and can also run tests through a configured HTTP runner.

Syntax highlighting works without BoxLang. The full feature set requires BoxLang CLI 1.17 or later, and the TestBox runner requires TestBox 7 or later. See the [TestBox BoxLang CLI Runner guide](/getting-started/running-tests/boxlang-cli-runner) for runner details, and the [Sublime Text package repository](https://github.com/ortus-boxlang/sublimetext-boxlang) for installation and configuration options.


# MXUnit Compatibility

Legacy Compatibility

{% hint style="danger" %}
Please note that this compatibility is now DEPRECATED and will be removed in a future release. We recommend migrating your tests to TestBox's native xUnit or BDD styles as soon as possible.
{% endhint %}

## MXUnit Compatibility

TestBox is fully compliant with [MXUnit](http://mxunit.org/) xUnit test cases. In order to leverage it you will need to create or override the `/mxunit` mapping and make it point to the `/testbox/system/compat` folder. That's it, everything should continue to work as expected.

> **Note** you will still need TestBox to be in the web root, or have a `/testbox` mapping created even when using the MXUnit compat runner.

```javascript
this.mappings[ "/mxunit" ] = expandPath( "/testbox/system/compat" );
```

After this, all your test code remains the same but it will execute through TestBox's xUnit runners. You can even execute them via the normal URL you are used to. If there is something that is not compatible, please let us know and we will fix it.

### Expected Exceptions

We also support in the compatibility mode the expected exception MXUnit annotation: `mxunit:expectedException` and the `expectException()` methods. The `expectException()` method is not part of the assertion library, but instead is inherited from our `BaseSpec.cfc`.

Please refer to MXUnit's documentation on the annotation and method for expected exceptions, but it is supported with one caveat. The `expectException()` method can produce unwanted results if you are running your test specs in TestBox asynchronous mode since it stores state at the component level. Only synchronous mode is supported if you are using the `expectException()` method. The annotation can be used in both modes.


# TestBox CLI

The official TestBox CLI for CommandBox — run, scaffold, watch, and manage your tests from the command line.

The **TestBox CLI** is a [CommandBox](https://www.ortussolutions.com/products/commandbox) module that brings test execution, scaffolding, watching, and project management directly to your terminal. It is the recommended way to interact with TestBox from the command line — especially for BoxLang projects.

## System Requirements

* CommandBox **6.x+**

## Installation

```bash
box install testbox-cli
```

Once installed, all `testbox` commands are available in your CommandBox shell. Use `--help` on any command to explore its options:

```bash
testbox run --help
testbox create bdd --help
testbox generate harness --help
```

***

## 🔍 Language Detection

The CLI automatically detects whether your project targets **BoxLang** 🟦 (primary) or **CFML** so that generated files use the correct syntax. Detection is applied in this order:

### BoxLang Detection

1. The server running in the current directory is a BoxLang server
2. `box.json` contains `testbox.runner=boxlang`
3. `box.json` contains `language=boxlang`

### CFML Detection (fallback)

1. The server running in the current directory is a CFML server (Lucee or Adobe ColdFusion)
2. `box.json` contains `language=cfml`

You can always override detection for any generator command using `--boxlang` or `--noBoxlang`.

***

## ▶️ Running Tests

The `testbox run` command executes your TestBox suite via HTTP and renders formatted results in the CLI.

### Basic Usage

```bash
# Uses testbox.runner from box.json
testbox run

# Pass a full URL directly
testbox run http://localhost:8080/tests/runner.cfm

# Use a relative path (requires a running CommandBox server in the current directory)
testbox run /tests/runner.cfm
```

### Named Runners

Define multiple named runner targets in `box.json` for different environments:

```json
"testbox": {
    "runner": [
        {
            "dev": "http://localhost:8080/tests/runner.cfm",
            "staging": "http://staging.myapp.com/tests/runner.cfm"
        }
    ]
}
```

Then target a specific runner by name:

```bash
testbox run dev
testbox run staging
```

### Filtering Tests

```bash
# Run a specific bundle
testbox run bundles=tests.specs.MyBDDSpec

# Run tests from a directory (dot notation)
testbox run directory=tests.specs

# Target a specific suite
testbox run testSuites="My Suite"

# Target a specific spec
testbox run testSpecs="it should do something"

# Filter by labels
testbox run labels=unit
testbox run labels=integration excludes=slow
```

### Verbose Output

By default only failing test details are shown. Use `--verbose` to include passing and skipped specs:

```bash
testbox run --verbose
```

### Ad-hoc URL Options

Pass arbitrary URL parameters to the runner, either inline or persisted in `box.json`:

```bash
# Inline
testbox run options:foo=bar options:env=dev

# Persisted
package set testbox.options.foo=bar
package set testbox.options.env=dev
```

### Output Formats for CI/CD

Produce multiple report formats from a single test run — all derived from the same JSON result:

```bash
# Generate JSON and ANT JUnit reports
testbox run outputFormats=json,antjunit

# With a custom output file name
testbox run outputFormats=json,antjunit,simple outputFile=myresults
```

Available formats: `json`, `xml`, `junit`, `antjunit`, `simple`, `dot`, `doc`, `min`, `mintext`, `text`, `tap`, `codexwiki`

### 🌊 Streaming Mode

Stream each spec result in real-time via Server-Sent Events (SSE) — no waiting for the full suite to finish:

```bash
testbox run --streaming
```

{% hint style="info" %}
Streaming requires your TestBox runner to support SSE output. This is available natively when running TestBox on BoxLang or a compatible CFML server.
{% endhint %}

### Configuring Defaults in `box.json`

Store your preferences in `box.json` so they apply automatically on every run:

```bash
package set testbox.runner=http://localhost:8080/tests/runner.cfm
package set testbox.verbose=true
package set testbox.labels=unit
package set testbox.testSuites=MySuite
```

***

## 👀 Watching Tests

The `testbox watch` command monitors your source files and automatically re-runs your tests whenever a file changes — great for a tight red/green/refactor loop.

### Basic Usage

```bash
# Start the watcher (uses testbox.runner from box.json)
testbox watch
```

On each detected change the screen clears and `testbox run` fires with your configured options. Press **Ctrl+C** to stop the watcher.

### Watch Options

```bash
# Watch specific file glob patterns
testbox watch paths=models/**.bx,tests/**.bx

# Adjust the polling delay (ms, minimum 150ms)
testbox watch delay=1000

# Scope to a directory or bundles
testbox watch directory=tests.specs
testbox watch bundles=tests.specs.MySpec

# Filter by labels
testbox watch labels=unit
```

### Configuring the Watcher in `box.json`

```bash
package set testbox.watchPaths=/models/**.bx,/tests/**.bx
package set testbox.watchDelay=1000
package set testbox.verbose=false
package set testbox.labels=unit
```

{% hint style="warning" %}
Make sure your server is already running and `testbox.runner` is configured in `box.json` before starting the watcher.
{% endhint %}

***

## 🏗️ Scaffolding

The `testbox create` commands scaffold new test files in either BoxLang or CFML based on your project's [language detection](#language-detection).

### Create a BDD Spec

```bash
# Create in the current directory
testbox create bdd MySpec

# Create in a specific directory
testbox create bdd MySpec directory=tests/specs

# Using dot notation for nested paths
testbox create bdd myPackage.MySpec

# Open the file in your editor after creation
testbox create bdd MySpec --open

# Force a specific language
testbox create bdd MySpec --boxlang
testbox create bdd MySpec --noBoxlang
```

**Generated BoxLang BDD Spec (`MySpec.bx`):**

```js
/**
 * My BDD Test
 */
class extends="testbox.system.BaseSpec" {

    function beforeAll() { }
    function afterAll() { }

    function run( testResults, testBox ) {
        describe( "My First Suite", () => {

            it( "A Spec", () => {
                fail( "implement" );
            } )

        } )
    }

}
```

### Create an xUnit Test

```bash
# Create in the current directory
testbox create unit MyTest

# Create in a specific directory
testbox create unit MyTest directory=tests/specs

# Using dot notation for nested paths
testbox create unit myPackage.MyTest

# Open the file in your editor after creation
testbox create unit MyTest --open
```

**Generated BoxLang xUnit Test (`MyTest.bx`):**

```js
/**
 * My xUnit Test
 */
class extends="testbox.system.BaseSpec" {

    function beforeTests() { }
    function afterTests() { }
    function setup( currentMethod ) { }
    function teardown( currentMethod ) { }

    @Test
    @DisplayName "A beautiful xUnit Test"
    function myMethodTest() {
        fail( "implement it" )
    }

}
```

***

## 🧪 Generating a Test Harness

The `testbox generate harness` command scaffolds a complete `tests/` directory for your project, including a runner, `Application.bx`/`Application.cfc`, and a sample spec — everything you need to start testing immediately.

```bash
# Generate in the current project
testbox generate harness

# Generate for a specific project path
testbox generate harness /path/to/myApp

# Force a specific language
testbox generate harness --boxlang
testbox generate harness --noBoxlang
```

{% hint style="info" %}
If TestBox is not already installed locally, the CLI will install it automatically before scaffolding the harness.
{% endhint %}

***

## 🌐 Generating a Test Browser

The `testbox generate browser` command creates a web-based test browser UI at `tests/browser/` — a convenient, visual way to browse and execute your test bundles from a browser.

```bash
# Generate in the current project
testbox generate browser

# Generate for a specific project path
testbox generate browser /path/to/myApp

# Force BoxLang
testbox generate browser --boxlang
```

The browser UI is placed at `tests/browser/` and can be accessed via your web server once your server is running.

***

## 📊 Generating a Test Visualizer

The `testbox generate visualizer` command generates a standalone HTML-based test results visualizer at `tests/test-visualizer/`. Load a JSON results file to get a rich visual breakdown of any test run.

```bash
# Generate in the current project
testbox generate visualizer

# Generate for a specific project path
testbox generate visualizer /path/to/myApp
```

**Using the visualizer:**

1. Run your tests with JSON output: `testbox run outputFormats=json outputFile=test-results`
2. Open `tests/test-visualizer/index.html` in your browser
3. Load the generated `test-results.json` file

***

## 📦 Generating a TestBox Module

The `testbox generate module` command scaffolds a new TestBox extension module — ideal for packaging custom matchers, reporters, or shared test helpers.

```bash
# Create a module in the current directory
testbox generate module myModule

# Create the module in a specific directory
testbox generate module myModule tests/resources/modules

# Force a specific language
testbox generate module myModule --boxlang
```

***

## 🔧 Installation Management

### View TestBox Info

Display which TestBox installation the CLI is currently using — local project copy or the CLI-bundled copy:

```bash
testbox info
```

The output shows the active version, the path on disk, and its source. If no TestBox is found anywhere, you will be prompted to install it.

### Reinstall the CLI Bundle

The CLI ships with its own bundled copy of TestBox used for output formatting and report generation. If this copy is outdated or corrupted, reinstall it:

```bash
# Reinstall the latest stable version
testbox reinstall

# Reinstall a specific version
testbox reinstall version=5.3.0

# Skip the confirmation prompt
testbox reinstall --force
testbox reinstall version=5.3.0 --force
```

{% hint style="warning" %}
`testbox reinstall` only affects the CLI-bundled copy of TestBox. It does **not** touch any TestBox installation inside your project.
{% endhint %}

***

## 📚 Documentation & Resources

Open the TestBox docs or API reference directly from the CLI:

```bash
# Open the TestBox documentation site
testbox docs

# Search the docs for a specific topic
testbox docs search=matchers
testbox docs search=mocking

# Open the TestBox API docs
testbox apidocs
```

***

## ⚡ Quick Reference

| Command                          | Description                              |
| -------------------------------- | ---------------------------------------- |
| `testbox run`                    | Execute tests via HTTP runner            |
| `testbox run --streaming`        | Stream test results in real-time via SSE |
| `testbox watch`                  | Watch files and re-run tests on change   |
| `testbox create bdd <name>`      | Scaffold a new BDD spec                  |
| `testbox create unit <name>`     | Scaffold a new xUnit test                |
| `testbox generate harness`       | Generate a full `tests/` harness         |
| `testbox generate browser`       | Generate a web-based test browser UI     |
| `testbox generate visualizer`    | Generate an HTML test results visualizer |
| `testbox generate module <name>` | Scaffold a new TestBox extension module  |
| `testbox info`                   | Show TestBox installation details        |
| `testbox reinstall`              | Reinstall the CLI-bundled TestBox        |
| `testbox docs`                   | Open TestBox documentation in a browser  |
| `testbox apidocs`                | Open TestBox API docs in a browser       |


# Writing Tests

Tests are placed inside of classes we lovingly call Test Bundles.

No matter what style you decide to use, you will still end up building a **Testing Bundle** Class. This class will either contain[ **BDD style** ](/getting-started/testbox-bdd-primer)suites and specs or [**xUnit style**](/getting-started/testbox-xunit-primer) method tests. You can create as many as you need and group them as necessary in different folders (packages) according to their features. Our test harness can be generated via the CLI or you can grab it from the installation folder `/bx or cfml/test-harness`. Here is the typical layout of the harness:

* `/tests` - The test harness
  * `/resources` - Where you can place any kind of testing helpers, data, etc
  * `/specs` - Where your test bundles can go
  * `Application.bx|cfc` - Your test harness applilcation file. Controls life-cycle and application concerns.
  * `runner.bx|cfm` - A web runner template that executes ALL your tests with tons of different options from a running web server.
  * `test.xml` - An ANT task to do JUNIT testing.

You will be creating test classes inside the `/tests/specs` folders. The class can extend our base class: `testbox.system.BaseSpec` or not. If you do, then the tests will be faster, executable directly from a web server and you will get IDE introspection. However, TestBox doesn't enforce the inheritance.

## My First Test

Typically test bundles are suffixed with the word `Test` or `Spec`, such as `MyServiceSpec.bx` or `UserServiceTest.cfc`

{% tabs %}
{% tab title="BoxLang" %}
{% code title="MyFirstSpec.bx" %}

```java
class extends="testbox.system.BaseSpec"{

    function run(){
	describe( "My First Test", ()=>{
	  test( "it can add", ()=>{
		expect( sum( 1, 2 ) ).toBe( 3 )
	  } )
	} )
    }

    private function sum( a, b ){
        return a + b
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="MyTest.cfc" %}

```cfscript
component extends="testbox.system.BaseSpec"{

    function run(){
	describe( "My First Test", ()=>{
	  test( "it can add", ()=>{
		expect( sum( 1, 2 ) ).toBe( 3 );
	  } );
	} );
    }

    private function sum( a, b ){
        return a + b;
    }

}
```

{% endcode %}
{% endtab %}
{% endtabs %}

The CLI can assist you when creating new bundles:

```bash
# Create a BDD Bundle
testbox create bdd --help
# Create an xUnit Bundle
testbox create unit --help

# Examples
# Remember that by convention it will create bundles at /tests/specs
testbox create bdd CalculatorTest --open
testbox create unit name=SecurityTest directory="tests/specs/unit/"
```

Now you can run your tests via the browser ([http://localhost:port/tests/runner.cfm](https://testbox.ortusbooks.com/getting-started/http:/localhost:port/tests/runner.cfm))

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b4d5ef95dc3679cfff95b8ff57072aefafa33048%2Freporters-simple-myfirsttest.png?alt=media" alt="The Simple reporter showing a passing My First Test"><figcaption><p>The Simple reporter in the browser</p></figcaption></figure>

or via the CLI `testbox run`

<div align="left"><figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/YMFxuqgODJOFnz44UYvk/image.png" alt=""><figcaption></figcaption></figure></div>

## Optional Inheritance

At runtime we provide the inheritance via mixins so you don't have to worry about it. However, if you want to declare the inheritance you can do so and this will give you the following benefits:

* Some IDEs will be able to give you introspection for methods and properties
* You will be able to use the HTML runner by executing directly the runRemote method on the CFC Bundle
* Your tests will run faster

## Injected Variables

At runtime, TestBox will inject several public variables into your testing bundle to help you with your testing.

* `$mockbox` : A reference to MockBox
* `$assert` : A reference to our Assertions library
* `$utility` : A utility CFC
* `$customMatchers` : A collection of custom matchers registered
* `$exceptionAnnotation` : The annotation used to discover expected exceptions, defaults to expectedException
* `$testID` : A unique identifier for the test bundle
* `$debugBuffer` : The debugging buffer stream

## Injected/Inherited Methods

Wether you inherit or not, your bundles will have a plethora of methods that will help you in your testing adeventure. Here is a link to the API Docs for the `BaseSpec` class:

{% embed url="<https://s3.amazonaws.com/apidocs.ortussolutions.com/testbox/current/index.html?testbox/system/BaseSpec>" %}
<https://s3.amazonaws.com/apidocs.ortussolutions.com/testbox/current/index.html?testbox/system/BaseSpec>
{% endembed %}

### Quick Assertion Methods

The BaseSpec has a few shortcut methods for quick assertions. Please look at the [Assertions](/digging-deeper/assertions) and [Expectations](/digging-deeper/expectations) library for more in-depth usage.

```javascript
// Assert that the expression is truthy
assert( expression, [message=""] )
// Start an expectation with an actual value, returns the Expectation object
expect( actual ) : Expectation
// Fail now!
fail( message )

// In BoxLang you can use the dynamic assertions feature
// Meaning you can execute any assertion method by just prefixing it with 
// the word `asssert{method}`
assertIsEqual()
assertIsTrue()
assertIsFalse()
... etc.
// This leverages the dynamic on missing method in BoxLang but not available in CFML
```

### Extension Methods

These methods allow you to extend TestBox with custom [assertions](/digging-deeper/assertions/custom-assertions) and expectation [matchers](/digging-deeper/expectations/custom-matchers).

```java
// extensions
addMatchers( struct|path matchers )
addAssertions( struct|path assertions )
```

### Environment Methods

These methods assist you with identifying environment conditions.

```java
// Which language/engine are you running on
isAdobe()
isLucee()
isBoxLang()

// What OS are we on
isLinux()
isMac()
isWindows()

// Get the Environment Class
getEnv()
```

{% hint style="info" %}
**Fixed in TestBox 7.1:** `isLucee()` used to return `true` under BoxLang, because BoxLang registers a `lucee` server scope key for compatibility. Specs that branched or skipped on engine took the Lucee path when running on BoxLang. `isLucee()` now returns `true` only on actual Lucee.
{% endhint %}

### Java Environment

You can use the `getEnv()` to get access to our Environment utility object. From there you can use the following methods:

```java
// Get a java property or environment setting or a default value
getSystemSetting( required key, [defaultValue] )

// Get a java system property ONLY
getSystemProperty( required key, [defaultValue] )

// Get a java environment setting ONLY
getEnv( required key, [defaultValue] )

// Get the java.lang.System
getJavaSystem()
```

### Utility Methods

These methods are here to help you during the testing process. Every bundle also get's a debug buffer attached to its running results. This is where you as the developer can send pretty much any variable (simple or complex) and attach it to the debug buffer. This will then be presented acordingly in the test reporters or facilities.

```java
// Send variables to the output console
console(any var, [numeric top='9999'], [boolean showUDFs='false'], [string label=''])
// Send data to the TestBox debug buffer
debug([any var], [string label=''], [boolean deepCopy='false'], [numeric top='999'], [boolean showUDFs='false'])
// Clear the buffer
clearDebugBuffer()
// Get the debug buffer
getDebugBuffer()

// Writes to the Output Buffer (CLI, Browser)
// Remember that if your test runs in the CLI, the buffer is the console
// If you are in a webserver, the buffer is the browser output
print( message )
printLn( message )
```

### Mocking Methods

TestBox is bundles with two amazing mocking facilities:

* **MockBox** - Mocks objects and stubs
* **MockDataCFC** - Allows you to mock data and JSON data - <https://www.forgebox.io/view/mockdatacfc>

```java
createMock([string className], [any object], [boolean clearMethods='false'])
createEmptyMock([string className], [any object], [boolean callLogging='true'])
prepareMock([any object], [boolean callLogging='true'])
createStub([boolean callLogging='true'], [string extends=''], [string implements=''])

// Create a mock query of data
querySim( queryData )
// Call the `mockData()` method on the MockDataCFC
mockData( arguments )

// Make a private/package method on a class public
makePublic(any target, string method, [string newName=''])
// Get the value of a private property on a class
getProperty( target, name, scope, defaultValue )

// Get the MockBox class
getMockBox( [string generationPath=''] )
```

### BDD Methods

These methods are used to create the BDD style of testing. You will discover them more in the [BDD Tests](/getting-started/testbox-bdd-primer) section.

```java
// Life-cycle methods
afterEach(any body, [struct data='[runtime expression]'])
aroundEach(any body, [struct data='[runtime expression]'])
beforeEach(any body, [struct data='[runtime expression]'])

// Suite/Grouping Methods
describe(string title, any body, [any labels='[runtime expression]'], [boolean asyncAll='false'], [any skip='false'], [boolean focused='false'])
feature(string title, any body, [any labels='[runtime expression]'], [boolean asyncAll='false'], [any skip='false'], [boolean focused='false'])
scenario(string title, any body, [any labels='[runtime expression]'], [boolean asyncAll='false'], [any skip='false'], [boolean focused='false'])
story(string title, any body, [any labels='[runtime expression]'], [boolean asyncAll='false'], [any skip='false'], [boolean focused='false'])
given(string title, any body, [any labels='[runtime expression]'], [boolean asyncAll='false'], [any skip='false'], [boolean focused='false'])
when(string title, any body, [any labels='[runtime expression]'], [boolean asyncAll='false'], [any skip='false'], [boolean focused='false'])

// skip the suite
xdescribe()
xfeature()
xscenario()
xgiven()
xstory()
xwhen()

// focus the suite
fdescribe()
ffeature()
fscenario()
fgiven()
fstory()
fwhen()


// Specs/Testing Methods
it(string title, any body, [any labels='[runtime expression]'], [any skip='false'], [struct data='[runtime expression]'], [boolean focused='false'])
then(string title, any body, [any labels='[runtime expression]'], [any skip='false'], [struct data='[runtime expression]'], [boolean focused='false'])
test(string title, any body, [any labels='[runtime expression]'], [any skip='false'], [struct data='[runtime expression]'], [boolean focused='false'])

// Skip the tests
xit()
xthen()
xtest()

// Focus the tests
fit()
fthen()
ftest()

// Start an expectation expression
expect( actual )
```


# Running Tests

Test All Things!

TestBox tests can be run from different sources from what we call **Runners.** These can be from different sources:

* CLI
  * TestBox CLI (Powered by CommandBox)
  * BoxLang Scripts
  * NodeJS
* Web Server / Browser
  * Web Runner
  * TestBundle Directly
  * **TestBox RUN IDE** (BoxLang-native browser IDE) 🆕
* Streaming (Real-Time)
  * **StreamingRunner** via SSE 🆕
* Custom

Your test harness already includes the web runner: `runner.bx or runner.cfm`. You can execute that directly in your browser to get the results or run it via the CLI: `testbox run`. We invite you to explore the different runners available to you.

{% content-ref url="/pages/ZV0rpTh2FmHDYit9Nfso" %}
[CommandBox Runner](/getting-started/running-tests/commandbox-runner)
{% endcontent-ref %}

{% content-ref url="/pages/lVHt8HyzaXFTHkZOtG8A" %}
[AI Agent Reporter](/getting-started/running-tests/ai-agent-reporter)
{% endcontent-ref %}

{% content-ref url="/pages/-LA-UiuSOsD\_50DMis05" %}
[Web Runner](/getting-started/running-tests/test-runner)
{% endcontent-ref %}

{% content-ref url="/pages/-LA-UiuRyDcQfY30r2qu" %}
[Bundle(s) Runner](/getting-started/running-tests/bundle-s-runner)
{% endcontent-ref %}

{% content-ref url="/pages/-LA-UiuT97dD2KzdojwR" %}
[Directory Runner](/getting-started/running-tests/directory-runner)
{% endcontent-ref %}

{% content-ref url="/pages/-LA-UiuWB8z9xAUkP7yt" %}
[ANT Runner](/getting-started/running-tests/ant-runner)
{% endcontent-ref %}

{% content-ref url="/pages/-LA-UiuXGJ-TP7gKuX\_L" %}
[NodeJS Runner](/getting-started/running-tests/nodejs-runner)
{% endcontent-ref %}

{% content-ref url="/pages/-LA-UiuQiOAxM\_s-OGqC" %}
[Test Browser](/getting-started/running-tests/test-browser)
{% endcontent-ref %}

{% content-ref url="/pages/EDpdkICeCJu01xXKmZyW" %}
[TestBox RUN IDE](/getting-started/running-tests/testbox-run-ide)
{% endcontent-ref %}

{% content-ref url="/pages/2RZVKzZXXh182rLMwI02" %}
[Streaming Runner](/getting-started/running-tests/streaming-runner)
{% endcontent-ref %}

### Custom Runners

However, you can create your own custom runners as long as you instantiate the `TestBox` class and execute one of it's runnable methods. The main execution methods are:

```javascript
// Run tests and produce reporter results
testbox.run()

// Run tests and get raw testbox.system.TestResults object
testbox.runRaw()

// Run tests and produce reporter results from SOAP, REST, HTTP
testbox.runRemote()

// Run via Spec URL
http://localhost/tests/spec.cfc?method=runRemote

// Via CommandBox
testbox run
```

{% hint style="info" %}
We encourage you to read the [API docs](http://apidocs.ortussolutions.com/testbox/current) included in the distribution for the complete parameters for each method.
{% endhint %}

## `run()`

Here are the arguments you can use for initializing TestBox or executing the `run()` method

```cfscript
/**
 * Run me some testing goodness, this can use the constructed object variables or the ones
 * you can send right here.
 *
 * @bundles      The path, list of paths or array of paths of the spec bundle classes to run and test
 * @directory    The directory to test which can be a simple mapping path or a struct with the following options: [ mapping = the path to the directory using dot notation (myapp.testing.specs), recurse = boolean, filter = closure that receives the path of the class found, it must return true to process or false to continue process ]
 * @reporter     The type of reporter to use for the results, by default is uses our 'simple' report. You can pass in a core reporter string type or an instance of a testbox.system.reports.IReporter. You can also pass a struct if the reporter requires options: {type="", options={}}
 * @labels       The list or array of labels that a suite or spec must have in order to execute.
 * @excludes     The list or array of labels that a suite or spec must not have in order to execute.
 * @options      A structure of configuration options that are optionally used to configure a runner.
 * @testBundles  A list or array of bundle names that are the ones that will be executed ONLY!
 * @testSuites   A list or array of suite names that are the ones that will be executed ONLY!
 * @testSpecs    A list or array of test names that are the ones that will be executed ONLY!
 * @callbacks    A struct of listener callbacks or a class with callbacks for listening to progress of the testing: onBundleStart,onBundleEnd,onSuiteStart,onSuiteEnd,onSpecStart,onSpecEnd
 * @eagerFailure If this boolean is set to true, then execution of more bundle tests will stop once the first failure/error is detected. By default this is false.
 */
any function run(
	any bundles,
	any directory,
	any reporter,
	any labels,
	any excludes,
	struct options,
	any testBundles      = [],
	any testSuites       = [],
	any testSpecs        = [],
	any callbacks        = {},
	boolean eagerFailure = false
)
```

* The `bundles` argument which can be a single CFC path or an array of CFC paths or a directory argument so it can go and discover the test bundles from that directory.
* The `reporter` argument can be a core reporter name like: json,xml,junit,raw,simple,dots,tap,min,etc or it can be an instance of a reporter CFC.
* You can execute the runners from any cfm template or any CFC or any URL, that is up to you.


# BoxLang CLI Runner

Run your tests directly with BoxLang in the CLI.

TestBox ships with a BoxLang CLI runner for Linux/Mac and Windows. Run your entire test suite — or individual bundles — directly from the terminal with rich, colored output, real-time streaming, dry runs, and detailed performance analysis.

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/t8AXFOUFnt08xKWQ3SHm/testbox-boxlang-reporter.png" alt="BoxLang CLI Runner output"><figcaption></figcaption></figure>

{% hint style="danger" %}
The BoxLang CLI runner is a BoxLang-only feature. It runs tests in the BoxLang OS runtime, not inside a web server.
{% endhint %}

BoxLang allows you to build web applications, CLI, serverless, Android, and more. You can use this runner to test each environment. However, please note that if you will be testing web apps from the CLI, you will need to install the web support module into the OS runtime.

### Web Server Testing

If you want to test your web application from the CLI without a running web server, install the `bx-web-support` module into the BoxLang OS runtime. This adds web BIFs, components, and a mock HTTP server so you can do full life-cycle testing purely from the CLI.

```bash
install-bx-module bx-web-support
```

{% hint style="success" %}
If you are building exclusively a web application, we suggest you use the [CommandBox runner](/getting-started/running-tests/commandbox-runner) which calls your runner via HTTP, or the [TestBox RUN IDE](/getting-started/running-tests/testbox-run-ide) for a browser-based experience.
{% endhint %}

### Application.bx Auto-Load

The BoxLang runner **automatically attempts to load your `Application.bx` mappings** from the project root before running any specs. This means custom path mappings, datasources, and settings defined in `Application.bx` are available to your tests without any extra configuration — bringing the CLI experience much closer to a full web server environment.

### Script Locations

The runner scripts live in `testbox/` inside your TestBox installation:

* `run` — Linux / macOS
* `run.bat` — Windows

The runner must be executed from the **root** of your BoxLang project.

### Examples

#### Mac/Linux

```bash
./testbox/run
./testbox/run my.bundle
./testbox/run --directory=tests.specs
./testbox/run --bundles=my.bundle
```

#### Windows

```bash
./testbox/run.bat
./testbox/run.bat my.bundle
./testbox/run.bat --directory=tests.specs
./testbox/run.bat --bundles=my.bundle
```

***

## Execution Options

| Option              | Description                                                                      | Default                                        |
| ------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------- |
| `--bundles`         | Dot-notation list of test bundles to run. Mutually exclusive with `--directory`. | `*`                                            |
| `--bundles-pattern` | Glob pattern for discovering bundles.                                            | `*Spec*.cfc\|*Test*.cfc\|*Spec*.bx\|*Test*.bx` |
| `--directory`       | Dot-notation directory to scan for tests. Mutually exclusive with `--bundles`.   | `tests.specs`                                  |
| `--recurse`         | Recurse into sub-directories.                                                    | `true`                                         |
| `--eager-failure`   | Stop the run on the first failure.                                               | `false`                                        |
| `--verbose`         | Show all spec results as they run.                                               | `false`                                        |

***

## 🌊 Streaming (Real-Time Output)

The `--stream` flag activates real-time output, pushing each spec result to the terminal as it completes rather than buffering until the suite finishes.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-cb55f78f3dfa4e29bcf6b3106ae78abd8fbeec27%2Ftestbox-boxlang-stream.gif?alt=media" alt="BoxLang CLI streaming output"><figcaption></figcaption></figure>

```bash
./testbox/run --stream
./testbox/run --directory=tests.specs --stream
```

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-a7e600c67cfa687142b96c0b5dba4ba4a6a6bc3b%2Ftestbox-boxlang-stream-options.gif?alt=media" alt="BoxLang CLI stream with options"><figcaption></figcaption></figure>

{% hint style="info" %}
Streaming is especially useful in CI environments where you need live progress rather than waiting for the full suite to finish before seeing any output.
{% endhint %}

***

## 🔍 Dry Run & Spec Discovery

The `--dry-run` flag discovers and reports every spec that **would** be executed — without actually running any spec closures. Use it to audit coverage, validate label filters, and build test inventories before committing to a full run.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-88da83c3344691bf9344a6868f0b908947734970%2Ftestbox-boxlang-dryrun.gif?alt=media" alt="BoxLang CLI dry run output"><figcaption></figcaption></figure>

```bash
# Formatted text output
./testbox/run --dry-run

# Raw JSON output — ideal for CI tools and external scripts
./testbox/run --dry-run=json
./testbox/run --dry-run=json --bundles=tests.specs.MySpec | jq .
```

The output lists every suite and spec that would be executed, along with their labels and any skip reasons.

{% hint style="success" %}
Dry run respects **all** the same filtering options as a normal run: `--labels`, `--bundles`, `--directory`, `--filter-suites`, `--filter-specs`, etc.
{% endhint %}

For programmatic dry runs from BoxLang code, see [Dry Run & Spec Discovery](/digging-deeper/dry-run).

***

## 🎯 Output & Focus Options (New in 7.0)

### `--show-failed-only`

Focus your terminal output exclusively on failures and errors, hiding all passing and skipped specs:

```bash
./testbox/run --show-failed-only
```

### `--show-passed` / `--show-skipped`

Fine-grained control over which result types appear in the output:

```bash
./testbox/run --show-passed=false    # hide passing specs
./testbox/run --show-skipped=false   # hide skipped specs
```

### `--stacktrace`

Control how much stack trace detail is shown for failures and exceptions:

```bash
./testbox/run --stacktrace=short   # default — condensed first frame only
./testbox/run --stacktrace=full    # complete Java/BoxLang stack trace
```

### `--max-failures`

Abort the run after a set number of failures — useful for keeping CI output manageable:

```bash
./testbox/run --max-failures=10
```

### Performance Analysis: `--slow-threshold-ms` & `--top-slowest`

Identify slow specs and surface them at the end of the run:

```bash
# Flag any spec taking longer than 500 ms as slow
./testbox/run --slow-threshold-ms=500

# Print a summary of the 5 slowest specs after the run
./testbox/run --top-slowest=5
```

### Combining Output Options

```bash
./testbox/run --show-failed-only --stacktrace=short --max-failures=5 --top-slowest=3
```

***

## Reporting Options

| Option                  | Description                                                                                                                                                             | Default           |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
| `--reporter`            | The reporter to use. Use `agent` for compact JSON built for AI agents, see [Reporters](/digging-deeper/reporters#agentreporter---token-efficient-output-for-ai-agents). | `text`            |
| `--reportpath`          | Directory for report files.                                                                                                                                             | `/tests/results`  |
| `--properties-summary`  | Generate a `.properties` summary file.                                                                                                                                  | `true`            |
| `--properties-filename` | Name for the properties file.                                                                                                                                           | `TEST.properties` |
| `--write-report`        | Write the report to a file.                                                                                                                                             | `true`            |
| `--write-json-report`   | Write a JSON report alongside the main report.                                                                                                                          | `false`           |
| `--write-visualizer`    | Write the test visualizer to the report directory.                                                                                                                      | `false`           |

***

## Retries, Failed Specs and Web Servers

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-fc2b174a7997b1ffce4ac7a82b60cedfed0f024c%2Ftestbox-web-server.gif?alt=media" alt="The BoxLang runner starting a MiniServer, running a browser spec and stopping the server"><figcaption><p>The BoxLang runner starting and stopping your web server</p></figcaption></figure>

These options shine for [browser tests](/browser-testing/browser-testing), but `--retries` and `--failed` work for every bundle, `.bx` or `.cfc`.

| Option                 | Description                                                                                                                                                                                                                   | Default                 |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------- |
| `--retries`            | How many extra times to run a failing or erroring spec. A spec `retries` argument and a bundle `retries` annotation take precedence. Skipped specs are never retried.                                                         | `0`                     |
| `--failed`             | Run only the bundles and specs that failed or errored in the last run, read from `{reportpath}/.testbox-failed.json`. Every run writes that file. When it is missing or lists nothing, a message is printed and nothing runs. | `false`                 |
| `--web-server`         | A shell command that starts a web server before the tests run, stopped with its child processes after the tests. Runs with `sh -c` (`cmd /c` on Windows) from the current directory.                                          |                         |
| `--web-server-url`     | The URL polled until the web server answers with a status below 500. Also the default `baseURL` of browser bundles.                                                                                                           | `http://localhost:8080` |
| `--web-server-timeout` | How long to wait for the web server to answer, in seconds. When it does not answer in time, the runner stops it, prints the reason and exits with code `1`.                                                                   | `60`                    |

```bash
# Start the app, run the browser specs, retry flaky ones once
./testbox/run --directory=tests.browser --web-server="boxlang-miniserver --port 8080" --retries=1

# Rerun only what failed last time
./testbox/run --failed
```

{% hint style="info" %}
Quote a `--web-server` command that contains spaces. When a launcher splits it at its spaces anyway, the runner joins the words after `--web-server=` back together until the next runner option, so a command whose own flags share a runner option name (such as `--directory`) belongs in a script. See [Running Browser Tests](/browser-testing/running-browser-tests) for the details and a CI example.
{% endhint %}

***

## Runner Options

Pass arbitrary options directly through to the selected runner:

```bash
--runner-{option}=value
```

***

## Filtering Options

| Option             | Description                                                                                   |
| ------------------ | --------------------------------------------------------------------------------------------- |
| `--labels`         | Only run specs/suites with these labels.                                                      |
| `--excludes`       | Skip specs/suites with these labels.                                                          |
| `--filter-bundles` | Limit execution to these bundle names.                                                        |
| `--filter-suites`  | Limit execution to these suite names. Direct name matching is supported at any nesting depth. |
| `--filter-specs`   | Limit execution to these spec names.                                                          |

{% hint style="info" %}
Suite filtering (`--filter-suites`) performs **direct name matching** at any nesting depth — if a suite's name exactly matches the filter value it will always be included regardless of how deeply it is nested.
{% endhint %}


# AI Agent Reporter

Return compact TestBox results for AI agents and automation.

The `AgentReporter` returns a compact, minified JSON summary designed for AI agents and automation. It includes run totals and failed or errored specs, without the full result details produced by the standard JSON reporter.

This is a **reporter**, not a separate test runner. Use it with a runner that supports the `agent` reporter:

{% tabs %}
{% tab title="BoxLang" %}
{% code title="BoxLang CLI runner" %}

```bash
./testbox/run --reporter=agent
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="CFML runner URL" %}

```
runner.cfm?reporter=agent&directory=tests.specs
```

{% endcode %}
{% endtab %}
{% endtabs %}

The JSON includes an `ok` status, run totals, a `failures` array, and a `truncated` count. See [AgentReporter options and output](/digging-deeper/reporters) for the complete schema and configuration options.


# CommandBox Runner

By installing the CommandBox [TestBox CLI](/getting-started/testbox-cli) you can access our CommandBox runner. The CommandBox runner leverages HTTP(S) to test against any running server. By default it reads your `box.json` for a `testbox.runner` entry, or falls back to `/tests/runner.cfm`.

```bash
testbox run
testbox run directory="tests.specs" outputFormats="json,junit,html"
testbox run runner="http://myremoteapp.com/tests/runner.cfm"
```

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/ksTIGnLApQI5kF75C2ln/image.png" alt="CommandBox runner output"><figcaption></figcaption></figure>

## Runner Options <a href="#default-runner-url" id="default-runner-url"></a>

If you type `testbox run --help` you can see all the arguments you can set for running your tests. However, please note that you can also pre-set them in your `box.json` under the `testbox` entry:

```json
"testbox":{
    "bundles":"",
    "directory":"tests.specs",
    "excludes":"",
    "labels":"",
    "options":{},
    "recurse":true,
    "reporter":"",
    "runner":[
        {
            "default":""
        }
    ],
    "testBundles":"",
    "testSpecs":"",
    "testSuites":"",
    "verbose":true,
    "watchDelay":500,
    "watchPaths":"**.cfc"
},
```

## Runner URL <a href="#default-runner-url" id="default-runner-url"></a>

You can also set up the default runner URL in your box.json and it will be used for you. Setting the URL is a one-time operation.

```bash
package set testbox.runner="http://localhost:8080/tests/runner.cfm"
testbox run
```

You can also use a relative path and CommandBox will look up the host and port from your server settings.

```bash
package set testbox.runner="/tests/runner.cfm"
testbox run
```

The default runner URL of the `testbox run` command is `/tests/runner.cfm` so there's actually no need to even configure it if you're using the default convention location for your runner.

### Multiple Runner URLs

You can define multiple URLs for your runners by using a JSON array of objects. Each key will be a nice identifier you can use via the `runner=key` argument in the command.

```json
"testbox" : {
    "runner" : [
        { "core"   : "http://localhost/tests/runner.cfm" },
        { "api" : "http://localhost/api/tests/runner.cfm" }
    ]
}
```

Then you can just pass in the name:

```bash
testbox run runner="core"
```

More Commands:

```bash
package set testbox.runner="[ { default : 'http://localhost/tests/runner.cfm' } ]" --append
package show testbox.runner
testbox run default
```

## Watcher

The CLI also comes with a code watcher and runner. It will watch any paths for you, and if it detects any changes, it will run the tests you want.

```bash
testbox watch help
```

In order for this command to work, you need to have started your server and configured the URL to the test runner in your `box.json`.

```bash
package set testbox.runner=http://localhost:8080/tests/runner.cfm
server start
testbox watch
```

You can also control what files to watch.

```bash
testbox watch **.bx
```

If you need more control over what tests run and their output, you can set additional options in your `box.json` which will be picked up automatically by `testbox run` when it fires.

```bash
package set testbox.verbose=false
package set testbox.labels=foo
package set testbox.testSuites=bar
package set testbox.watchDelay=1000
package set testbox.watchPaths=/models/**.bx
```

This command will run in the foreground until you stop it. When you are ready to shut down the watcher, press `Ctrl+C`.

## 🌊 Streaming (Real-Time Results)

The `--streaming` flag taps into the new `StreamingRunner` to deliver each spec result to your terminal in real time via Server-Sent Events (SSE) — no waiting for the full suite to finish.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-dd34290899e5bd18766d6109772eeef7b7c31a75%2Ftestbox-cli-streaming-runner.gif?alt=media" alt="CLI streaming runner real-time output"><figcaption></figcaption></figure>

```bash
testbox run --streaming
```

Pair with `--verbose` to include all passing specs in the live feed (by default only failures and skipped specs persist after the run):

```bash
testbox run --streaming --verbose
```

{% hint style="info" %}
Streaming works best with BoxLang, but can be used with CFML engines that support SSE as well. See [Streaming Runner](/getting-started/running-tests/streaming-runner) for the underlying API.
{% endhint %}

[<br>](https://commandbox.ortusbooks.com/testbox-integration/test-runner)


# Web Runner

Every test harness comes with a `runner.bx or runner.cfm` in the root of the `tests` folder. This is called the web runner and is executable via the web server you are running your application on. This will execute all the tests by convention found in the `tests/specs` folder.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b4d5ef95dc3679cfff95b8ff57072aefafa33048%2Freporters-simple-myfirsttest.png?alt=media" alt="The web runner with the Simple reporter"><figcaption><p>The web runner with the default Simple reporter</p></figcaption></figure>

```
http://localhost/tests/runner.cfm
```

You can open that file and customize it as you see fit. Here is an example of such a file:

```xml
<!--- Executes all tests in the 'specs' folder with simple reporter by default --->
<bx:param name="url.reporter" 			default="simple">
<bx:param name="url.directory" 			default="tests.specs">
<bx:param name="url.recurse" 			default="true" type="boolean">
<bx:param name="url.bundles" 			default="">
<bx:param name="url.labels" 			 default="">
<bx:param name="url.excludes" 			 default="">
<bx:param name="url.reportpath" 		 default="#expandPath( "/tests/results" )#">
<bx:param name="url.propertiesFilename"  default="TEST.properties">
<bx:param name="url.propertiesSummary"	default="false" type="boolean">
<bx:param name="url.editor" 			  default="vscode">
<bx:param name="url.bundlesPattern" 	 default="*Spec*.cfc|*Test*.cfc|*Spec*.bx|*Test*.bx">

<!--- Code Coverage requires FusionReactor --->
<bx:param name="url.coverageEnabled"			default="false">
<bx:param name="url.coveragePathToCapture"		default="#expandPath( '/root' )#">
<bx:param name="url.coverageWhitelist"			  default="">
<bx:param name="url.coverageBlacklist"			  default="/testbox,/coldbox,/tests,/modules,Application.cfc,/index.cfm,Application.bx,/index.bxm">
<!---<bx:param name="url.coverageBrowserOutputDir"		default="#expandPath( '/tests/results/coverageReport' )#">--->
<!---<bx:param name="url.coverageSonarQubeXMLOutputPath"	default="#expandPath( '/tests/results/SonarQubeCoverage.xml' )#">--->
<!--- Enable batched code coverage reporter, useful for large test bundles which require spreading over multiple testbox run commands. --->
<!--- <bx:param name="url.isBatched"						default="false"> --->

<!--- Include the TestBox HTML Runner --->
<bx:include template="/testbox/system/runners/HTMLRunner.cfm" >
```

### Run All and Run Failed

The HTML reports (`Simple`, `Min`, `Dot`, `Doc`) have a **Run All** button and, when something failed or errored, a **Run Failed (N)** button that reruns only those specs through the same runner. The link carries the failed bundles and spec ids (`testBundles` and `testSpecs`), so the runner keeps no state. See [Run All and Run Failed](/digging-deeper/reporters#run-all-and-run-failed).

### Test Bundle Execution

If you make your test bundle class inherit from our `testbox.system.BaseSpec` class, you will be able to execute the class directly via the URL:

```javascript
// BoxLang
http://localhost/tests/specs/MyFirstTest.bx?method=runRemote

// CFML
http://localhost/tests/specs/MyFirstTest.cfc?method=runRemote
```

### Arguments

All the arguments found in the `runner` are available as well in a direct bundle execution:

* `labels`: The labels to apply to the execution
* `testMethod` : A list or array of xunit test names that will be executed ONLY!
* `testSuites` : A list or array of suite names that are the ones that will be executed ONLY!
* `testSpecs` : A list or array of test names that are the ones that will be executed ONLY!
* `reporter` : The type of reporter to run the test with

```javascript
// BoxLang
http://localhost/tests/specs/MyFirstTest.bx?method=runRemote&reporter=text

// CFML
http://localhost/tests/specs/MyFirstTest.cfc?method=runRemote&reporter=text
```


# Bundle(s) Runner

This is more of an approach than an actual specifc runner. This approach shows you that you can create a script file in BoxLang (`bxs`) or in CFML (`cfs|cfm`) that can in turn execute any test bundle(s) with many many runnable configurations.

### BoxLang

The BoxLang language allows you to run your scripts via the CLI or the browser if you have a web server attached to your project.

{% code title="run.bxs" %}

```js
// Test the BDD Bundle
r = new testbox.system.TestBox( "tests.specs.BDDTest" )
println( r.run() );

// Test the bundle with ONLY the passed specs
r = new testbox.system.TestBox( "tests.specs.BDDTest" )
println( r.run( testSpecs="OnlyThis,AndThis,AndThis" ) )

// Test the bundle with ONLY the passed suites
r = new testbox.system.TestBox( "tests.specs.BDDTest" )
println( r.run( testSuites="Custom Matchers,A Spec" ) )

// Test the passed array of bundles
r = new testbox.system.TestBox( [ "tests.specs.BDDTest", "tests.specs.BDD2Test" ] )
println( r.run() )

// Test with labels and the minimal reporter
r = new testbox.system.TestBox( bundles: "tests.specs.BDDTest", labels="linux" )
println( r.run( reporter: "mintext" ) )
```

{% endcode %}

If you want to run it in the CLI, then just use:

```bash
boxlang run.bxs
```

If you want to run it via the web server, place it in your `/tests/` folder and run it

```
http://localhost/tests/run.bxs
```

### CFML

CFML engines only allow you to run tests via the browser. So create your script, place it in your web accessible `/tests` folder and run it.

{% code title="run.cfm" %}

```cfscript
<cfscript>
	// Test the BDD Bundle
	r = new testbox.system.TestBox( "tests.specs.BDDTest" )
	writeOutput( r.run() );

	// Test the bundle with ONLY the passed specs
	r = new testbox.system.TestBox( "tests.specs.BDDTest" )
	writeOutput( r.run( testSpecs="OnlyThis,AndThis,AndThis" ) )

	// Test the bundle with ONLY the passed suites
	r = new testbox.system.TestBox( "tests.specs.BDDTest" )
	writeOutput( r.run( testSuites="Custom Matchers,A Spec" ) )

	// Test the passed array of bundles
	r = new testbox.system.TestBox( [ "tests.specs.BDDTest", "tests.specs.BDD2Test" ] )
	writeOutput( r.run() )

	// Test with labels and the minimal reporter
	r = new testbox.system.TestBox( bundles: "tests.specs.BDDTest", labels="linux" )
	writeOutput( r.run( reporter: "mintext" ) )
</cfscript>
```

{% endcode %}


# Directory Runner

This is more of an approach than an actual specifc runner. This approach shows you that you can create a script file in BoxLang (`bxs`) or in CFML (`cfs|cfm`) that can in turn execute any test directory with many many runnable configurations. It is very similar to the [Bundle Runner](/getting-started/running-tests/bundle-s-runner) approach.

### BoxLang

The BoxLang language allows you to run your scripts via the CLI or the browser if you have a web server attached to your project.

{% code title="run.bxs" %}

```groovy
// Run all the specs in the tests.specs directory and subdirectories
r = new testbox.system.TestBox( directory="tests.specs" )
println( r.run() )

// Run all the specs in the tests.specs directory ONLY
r = new testbox.system.TestBox(
		directory={
            mapping="tets.specs",
            recurse=false
      } )
println( r.run() )

// Run all the specs in the tests.specs directory and subdirectories using
// a custom lambda filter
r = new testbox.system.TestBox(
      	directory={
            mapping : "tets.specs",
            filter : path -> findNoCase( "test", arguments.path ) ? true : false
      }) >
println( r.run() )

// Run all the specs in the tests.specs directory and subdirectories using
// a custom lambda filter and create a JSON report
r = new testbox.system.TestBox(
      	directory={
            mapping="tets.specs",
            filter : path -> findNoCase( "test", arguments.path ) ? true : false
      }) >
fileWrite( 'testreports.json', r.run() )
println( "JSON report created" )
```

{% endcode %}

If you want to run it in the CLI, then just use:

```bash
boxlang run.bxs
```

If you want to run it via the web server, place it in your `/tests/` folder and run it

```
http://localhost/tests/run.bxs
```

### CFML

CFML engines only allow you to run tests via the browser. So create your script, place it in your web accessible `/tests` folder and run it.

```xml
<cfset r = new testbox.system.TestBox( directory="tests.specs" ) >
<cfoutput>#r.run()#</cfoutput>

<cfset r = new testbox.system.TestBox(
      directory={
            mapping="tets.specs",
            recurse=false
      }) >
<cfoutput>#r.run()#</cfoutput>

<cfset r = new testbox.system.TestBox(
      directory={
            mapping="tets.specs",
            recurse=true,
            filter=function(path){
                  return ( findNoCase( "test", arguments.path ) ? true : false );
            }
      }) >
<cfoutput>#r.run()#</cfoutput>

<cfset r = new testbox.system.TestBox(
      directory={
            mapping="tets.specs",
            recurse=true,
            filter=function(path){
                  return ( findNoCase( "test", arguments.path ) ? true : false );
            }
      }) >
<cfset fileWrite( 'testreports.json', r.run() )>
```


# ANT Runner

In our test harness we include an ANT runner (`test.xml`) that will be able to execute your tests via ANT.

{% hint style="info" %}
**Ant** is a Java-based build tool from Apache designed to automate the software build process. Unlike traditional build tools that rely on shell commands, Ant uses XML to describe the build process and its dependencies, making it platform-independent and flexible. It is particularly useful for Java projects to compile code, manage dependencies, and create deployment packages.\
<https://ant.apache.org/bindownload.cgi>
{% endhint %}

It can also leverage our `ANTJunit` reporter to use the `junitreport` task to produce JUnit compliant reports as well.

```xml
<?xml version="1.0"?>
<--<
This ANT build can be used to execute your tests with automation using our included runner.cfm.
You can executes directories, bundles and so much more.  It can also produce JUnit reports using the
ANT junitreport tag.  This is meant to be a template for you to spice up.

There are two targets you can use: run and run-junit

Execute the default 'run' target
ant -f test.xml
OR
ant -f test.xml run

Execute the 'run-junit' target
ant -f test.xml run-junit

PLEASE NOTE THAT YOU MUST ALTER THE RUNNER'S URL ACCORDING TO YOUR ENVIRONMENT.
-->
<project name="testbox-ant-runner" default="run" basedir=".">

     <-- <THE URL TO THE RUNNER, PLEASE CHANGE ACCORDINGLY-->
     <property name="url.runner"             value="http://localhost/tests/runner.cfm?"/>
     <-- <FILL OUT THE BUNDLES TO TEST, CAN BE A LIST OF CFC PATHS -->
     <property name="test.bundles"      value="" />
     <-- <FILL OUT THE DIRECTORY MAPPING TO TEST -->
     <property name="test.directory"         value="test.specs" />
     <-- <FILL OUT IF YOU WANT THE DIRECTORY RUNNER TO RECURSE OR NOT -->
     <property name="test.recurse"      value="true" />
     <-- <FILL OUT THE LABELS YOU WANT TO APPLY TO THE TESTS -->
     <property name="test.labels"       value="" />
     <-- <FILL OUT THE TEST REPORTER YOU WANT, AVAILABLE REPORTERS ARE: ANTJunit, Codexwiki, console, dot, doc, json, junit, min, raw, simple, tap, text, xml -->
     <property name="test.reporter"          value="simple" />
     <-- <FILL OUT WHERE REPORTING RESULTS ARE STORED -->
     <property name="report.dir"        value="${basedir}/results" />
     <property name="junitreport.dir"   value="${report.dir}/junitreport" />

     <target name="init" description="Init the tests">
          <mkdir dir="${junitreport.dir}" />
          <tstamp prefix="start">
               <format property="TODAY" pattern="MM-dd-YYYY hh:mm:ss aa"/>
          </tstamp>
          <concat destfile="${report.dir}/latestrun.log">Tests ran at ${start.TODAY}</concat>
     </target>

     <target name="run" depends="init" description="Run our tests and produce awesome results">

          <-- <Directory Runner
               Executes recursively all tests in the passed directory and stores the results in the
               'dest' param.  So if you want to rename the file, do so here.

                Available params for directory runner:
                - Reporter
                - Directory
                - Recurse
                - Labels
          -->
          <get dest="${report.dir}/results.html"
                src="${url.runner}&directory=${test.directory}&recurse=${test.recurse}&reporter=${test.reporter}&labels=${test.labels}"
                verbose="true"/>

          <-- <Bundles Runner
               You can also run tests for specific bundles by using the runner with the bundles params

               Available params for runner:
                - Reporter
                - Bundles
                - Labels

          <get dest="${report.dir}/results.html"
                src="${url.runner}&bundles=${test.bundles}&reporter=${test.reporter}&labels=${test.labels}"
                verbose="true"/>
           -->

     </target>

     <target name="run-junit" depends="init" description="Run our tests and produce ANT JUnit reports">

          <-- <Directory Runner
               Executes recursively all tests in the passed directory and stores the results in the
               'dest' param.  So if you want to rename the file, do so here.

                Available params for directory runner:
                - Reporter = ANTJunit fixed
                - Directory
                - Recurse
                - Labels
                - ReportPath : The path where reports will be stored, by default it is the ${report.dir} directory.
          -->
          <get dest="${report.dir}/results.xml"
                src="${url.runner}&directory=${test.directory}&recurse=${test.recurse}&reporter=ANTJunit&labels=${test.labels}&reportPath=${report.dir}"
                verbose="true"/>

          <-- <Bundles Runner
               You can also run tests for specific bundles by using the runner with the bundles params

               Available params for runner:
                - Reporter
                - Bundles
                - Labels

          <get dest="${report.dir}/results.html"
                src="${url.runner}&bundles=${test.bundles}&reporter=${test.reporter}&labels=${test.labels}"
                verbose="true"/>
           -->

           <-- <Create fancy junit reports -->
          <junitreport todir="${junitreport.dir}">
               <fileset dir="${report.dir}">
                    <include name="TEST-*.xml"/>
               </fileset>
               <report format="frames" todir="${junitreport.dir}">
                    <param name="TITLE" expression="My Awesome TestBox Results"/>
               </report>
          </junitreport>

     </target>

</project>
```

Now you can run the commands

```bash
# Execute the default 'run' target
ant -f test.xml
# Execute a specific target
ant -f test.xml run-junit
```


# NodeJS Runner

There is a user-contributed NodeJS Runner that looks fantastic and can be downloaded here: <https://www.npmjs.com/package/testbox-runner>

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/rKxmqnRi4C9SPqaZWWS2/testbox-node.png)

You can use node to install as well into your projects.

```bash
npm install -g testbox-runner
```

### Configuration

Create a config file called `.testbox-runnerrc` in the root of your web project.

```json
{
	"runner": "http://localhost/testbox/system/runners/HTMLRunner.cfm",
	"directory": "/tests/specs",
	"recurse": true
}
```

Then use the CLI command to run whatever you configured.

`testbox-runner`

You can also specify a specific configuration file:

`testbox-runner --config /path/to/config/file.json`

#### Command Line Arguments

Simply run the utility and pass the above configuration options prefixed with `--`.

**Example**

```bash
testbox-runner 
    --runner http://localhost/testbox/system/runners/HTMLRunner.cfm 
    --directory /tests 
    --recurse true
```


# Test Browser

TestBox ships with a test browser that is highly configurable to whatever URL accessible path you want. It will then show you a test browser where you can navigate and execute not only individual tests, but also directory suites as well.

* BoxLang: `/testbox/bx/browser`
* CFML: `/testbox/cfml/browser`

It is also a mini web application that can be configured to whatever root folder you desire. It will read the runners and tests from that folder and present a GUI that you can use to navigate the test folders and execute them easily.

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/opCSmdsW9LJZMaL5Svt1/image.png" alt=""><figcaption></figcaption></figure>


# TestBox RUN IDE

The BoxLang-native browser IDE for discovering, running, and streaming your test results in real time.

**TestBox RUN** is a brand-new, BoxLang-native test runner and IDE shipped as part of TestBox 7. It is a fully-featured browser-based interface for discovering, running, and streaming your test results in real time — all powered by BoxLang and the new `StreamingRunner` SSE engine.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b75a32f56aca939912a78a80d63affb60323d894%2Ftestbox-run.gif?alt=media" alt="TestBox RUN IDE in action"><figcaption><p>TestBox RUN — real-time streaming test results in the browser</p></figcaption></figure>

{% hint style="info" %}
TestBox RUN is **BoxLang-only**. It requires a running web server and a `runner.bxm` (or `runner.bx`) endpoint that supports the SSE streaming protocol. For pure CLI applications, use the [BoxLang CLI runner](/getting-started/running-tests/boxlang-cli-runner) with `--stream` instead.
{% endhint %}

## What Is It?

TestBox RUN is a self-hosted single-page web app (`bx/tests/index.bxm`) that you drop into your BoxLang project and open in your browser. It communicates with your existing `runner.bxm` endpoint and streams spec results as they complete via **Server-Sent Events**. No build toolchain, no external service — just BoxLang.

## Getting Started

TestBox RUN is included automatically with every TestBox 7 installation under `bx/tests/`. Point your web server at `bx/tests/index.bxm` and open it in your browser.

Every ColdBox application generated with the `ColdBox CLI` also includes TestBox RUN out of the box.

You can also scaffold a new test harness with TestBox RUN support using the TestBox CLI:

```bash
testbox generate harness --boxlang
```

### URL Parameters

Every setting can be overridden via URL query parameters for quick CI integration or bookmarking specific runs:

```
/tests/?directory=tests.specs.integration&labels=slow&runnerUrl=/tests/runner.bxm
```

***

## Feature Highlights

### Real-Time Streaming Test Tree

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-063893771ff35546d7f38889fb7f03e80a354eb8%2Ftestbox-suite-run.gif?alt=media" alt="Suite running in real-time"><figcaption><p>Results appear as each spec finishes — no waiting for the full suite</p></figcaption></figure>

Results appear in the UI as each spec finishes. The test tree updates live — passing specs turn green ✅, failures show red ❌, and errors surface immediately with their full message — long before the suite finishes.

***

### Beautiful, Responsive UI

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-4eedb6dcfd39699681493052ec69a13e7ce56c84%2Ftestbox-run-help.png?alt=media" alt="TestBox RUN UI overview"><figcaption></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-59873e9fdb6a57fb2d0ebdf0b128173f735a7e4d%2Ftestbox-run-light.png?alt=media" alt="TestBox RUN light mode"><figcaption><p>Both dark and light themes are supported</p></figcaption></figure>

* **Dark / Light theme toggle** with preference persistence in `localStorage`
* **Keyboard-first UX** — see keyboard shortcuts below

***

### Keyboard Shortcuts

| Shortcut         | Action                             |
| ---------------- | ---------------------------------- |
| `⌘/Ctrl + K`     | Focus the search bar               |
| `Esc`            | Clear search                       |
| `⌘/Ctrl + Enter` | Run all tests                      |
| `⌘/Ctrl + .`     | Reload / rediscover tests          |
| `⌘/Ctrl + ,`     | Open Settings                      |
| `⌘/Ctrl + B`     | Toggle expand/collapse all bundles |
| `⌘/Ctrl + D`     | Toggle dark/light mode             |
| `⌘/Ctrl + H`     | Open the About / Help dialog       |

***

### Live Search & Filtering

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-50efe216a8008d5b8a6592dfab05c1ab1cdae799%2Ftestbox-run-search.gif?alt=media" alt="Live search filtering the test tree"><figcaption><p>Instantly filter by bundle, suite, or spec name</p></figcaption></figure>

A **search bar** at the top lets you instantly filter the test tree by bundle, suite, or spec name. Combined with the **status filter chips** (Passed / Failed / Errored / Skipped), you can zero in on exactly the tests you care about.

***

### Per-Bundle Run

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-8607eb107ab46ae58328b23abea5c2d56f975d54%2Ftestbox-run-bundle-run.gif?alt=media" alt="Running a single bundle"><figcaption><p>Re-run a single bundle without rerunning the entire suite</p></figcaption></figure>

Each bundle card has its own **▶ Run** button so you can re-run a single bundle without triggering the full suite. A compact **results strip** beneath each bundle header shows pass/fail/error/skipped counts and total duration at a glance.

***

### Debug Buffer Panel

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-833a28e71ef3a1826d042828c03fb4fb9cdc73ee%2Ftestbox-run-debug-buffer.gif?alt=media" alt="Debug buffer panel"><figcaption><p>Per-bundle debug output captured during a run</p></figcaption></figure>

Any output captured in the TestBox debug buffer during a run is surfaced in a collapsible per-bundle **Debug Panel**, accessible via the bug icon on the bundle strip. Each entry is rendered with its label and a formatted data view.

***

### Floating Progress Widget

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0adef9b1ce1ebd0f65458b348f85fa9930a86abb%2Ftestbox-run-progress-bar.gif?alt=media" alt="Floating progress widget"><figcaption><p>Live progress during an active run</p></figcaption></figure>

A floating progress widget appears during active runs, showing:

* Current bundle running
* Specs completed vs. total
* Animated progress bar with percentage

***

### Configurable Settings

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-036f5558d839074e0e45bf48a3eed0c3508bc3ea%2Ftestbox-run-settings.gif?alt=media" alt="Settings modal"><figcaption><p>Configure runner URL, directory, bundles, labels, and more</p></figcaption></figure>

Click the gear icon (or `⌘/Ctrl + ,`) to open the **Settings modal**, where you can configure:

* Runner URL (relative path or absolute HTTP/S)
* Directory and bundles pattern
* Recurse toggle
* Labels and excludes

All settings are saved in `localStorage` and applied on the next visit.

***

## Coming Soon: TestBox RUN Desktop App

{% hint style="success" %}
We are actively working on a **native desktop application** version of TestBox RUN, built entirely on the **BoxLang Desktop Runtime**. The desktop app will connect to any web-accessible runner URL — local or remote — and provide the same real-time streaming UI without a browser.

Stay tuned at [testbox.run](https://www.testbox.run) for announcements, early access, and previews.
{% endhint %}


# Streaming Runner

Push test results to clients in real time via Server-Sent Events as each spec completes.

TestBox 7 introduces a brand-new **StreamingRunner** that pushes test results to the client as each spec completes via **Server-Sent Events (SSE)**. You no longer have to wait for the entire suite to finish before seeing results — each spec result is streamed in real time. This opens up powerful workflows for CI pipelines, large test suites, and browser-based IDEs where immediate feedback is critical.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-dd34290899e5bd18766d6109772eeef7b7c31a75%2Ftestbox-cli-streaming-runner.gif?alt=media" alt="Streaming runner real-time output"><figcaption><p>Spec results arrive in the terminal as each test completes</p></figcaption></figure>

## Where Streaming Is Used

The `StreamingRunner` is the engine behind two separate streaming experiences:

| Consumer                                                              | How to activate                                                    |
| --------------------------------------------------------------------- | ------------------------------------------------------------------ |
| [**TestBox RUN IDE**](/getting-started/running-tests/testbox-run-ide) | Open `bx/tests/index.bxm` in your browser — streaming is always on |
| **CommandBox CLI**                                                    | `testbox run --streaming`                                          |
| **BoxLang CLI Runner**                                                | `./testbox/run --stream`                                           |

***

## Programmatic Usage

`testbox.system.runners.StreamingRunner` can be wired into any SSE-capable HTTP endpoint:

```javascript
component {

    function streamTests( event, rc, prc ) {
        // Required SSE headers
        event.setHTTPHeader( name = "Content-Type",  value = "text/event-stream" );
        event.setHTTPHeader( name = "Cache-Control", value = "no-cache" );
        event.setHTTPHeader( name = "Connection",    value = "keep-alive" );

        new testbox.system.runners.StreamingRunner(
            bundles  = "tests.specs",
            options  = {},
            reporter = "text"
        ).run();
    }

}
```

### BoxLang Example

In a BoxLang handler or script:

```javascript
class {

    function streamTests( event, rc, prc ) {
        event.setHTTPHeader( name = "Content-Type",  value = "text/event-stream" )
        event.setHTTPHeader( name = "Cache-Control", value = "no-cache" )

        new testbox.system.runners.StreamingRunner(
            bundles = "tests.specs",
            options = {}
        ).run()
    }

}
```

***

## CLI Streaming

### CommandBox (`testbox run --streaming`)

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-dd34290899e5bd18766d6109772eeef7b7c31a75%2Ftestbox-cli-streaming-runner.gif?alt=media" alt="CommandBox streaming results"><figcaption></figcaption></figure>

```bash
testbox run --streaming

# Include all passing specs in the live feed
testbox run --streaming --verbose
```

### BoxLang CLI (`./testbox/run --stream`)

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-cb55f78f3dfa4e29bcf6b3106ae78abd8fbeec27%2Ftestbox-boxlang-stream.gif?alt=media" alt="BoxLang CLI streaming output"><figcaption></figcaption></figure>

```bash
./testbox/run --stream
./testbox/run --directory=tests.specs --stream
```

See the [BoxLang CLI Runner](/getting-started/running-tests/boxlang-cli-runner) for the full set of output-control options (`--show-failed-only`, `--stacktrace`, etc.) that work alongside `--stream`.

***

## SSE Event Format

Each spec result is emitted as an SSE event with the following structure:

```
event: spec
data: {"name":"it should do something","status":"pass","durationMs":12,"suitePath":"My Suite > My Sub Suite"}

event: spec
data: {"name":"it should fail","status":"fail","durationMs":5,"message":"Expected true to be false"}

event: done
data: {"totalPass":42,"totalFail":1,"totalError":0,"totalSkipped":3,"totalDuration":1402}
```

Event types:

| Event          | Description                                        |
| -------------- | -------------------------------------------------- |
| `bundle-start` | A new bundle begins execution                      |
| `bundle-end`   | A bundle has finished; includes bundle-level stats |
| `suite-start`  | A suite begins                                     |
| `suite-end`    | A suite completes                                  |
| `spec`         | A single spec result (pass/fail/error/skipped)     |
| `done`         | Full run complete; includes aggregate stats        |

{% hint style="info" %}
The SSE format is consumed natively by the [TestBox RUN IDE](/getting-started/running-tests/testbox-run-ide) and by the streaming renderers in both CLI runners. You can also consume it from any SSE-capable HTTP client.
{% endhint %}


# BDD Tests

**BDD** stands for Behavioral Driven Development. It is a software development process that aims to improve collaboration between developers, testers, and business stakeholders. BDD involves creating automated tests that are based on the expected behavior of the software, rather than just testing individual code components. This approach helps ensure that the software meets the desired functionality and is easier to maintain and update in the future.

In traditional xUnit, you focused on every component's method individually. In BDD, we will focus on a `feature` or `story` to complete, which could include testing many different components to satisfy the criteria. TestBox allows us to create these types of texts with human-readable functions matching our features/stories and expectations.

```cfscript
describe( "Tests of TestBox behaviour", () => {
	it( "rejects 5 as being between 1 and 10", () => {
		expect( () => {
			expect( 5 ).notToBeBetween( 1, 10 );
		} ).toThrow();
	} );
	
	it( "rejects 10 as being between 1 and 10", () => {
		expect( () => {
			expect( 10 ).notToBeBetween( 1, 10 );
		} ).toThrow();
	} );
} );


feature( "Given-When-Then test language support", () => {
	scenario( "I want to be able to write tests using Given-When-Then language", () => {
		given( "I am using TestBox", () => {
			when( "I run this test suite", () => {
				then( "it should be supported", () => {
					expect( true ).toBe( true );
				} );
			} );
		} );
	} );
} );

story( "I want to list all authors", () => {
    given( "no options", () => {
        then( "it can display all active system authors", () => {
            var event = this.get( "/cbapi/v1/authors" );
            expect( event.getResponse() ).toHaveStatus( 200 );
            expect( event.getResponse().getData() ).toBeArray().notToBeEmpty();
            event
                .getResponse()
                .getData()
                .each( function( thisItem ){
                    expect( thisItem.isActive ).toBeTrue( thisItem.toString() );
                } );
        } );
    } );
    given( "isActive = false", () => {
        then( "it should display inactive users", () => {
            var event = this.get( "/cbapi/v1/authors?isActive=false" );
            expect( event.getResponse() ).toHaveStatus( 200 );
            expect( event.getResponse().getData() ).toBeArray().notToBeEmpty();
            event
                .getResponse()
                .getData()
                .each( function( thisItem ){
                    expect( thisItem.isActive ).toBeFalse( thisItem.toString() );
                } );
        } );
    } );
    given( "a search criteria", () => {
        then( "it should display searched users", () => {
            var event = this.get( "/cbapi/v1/authors?search=tester" );
            expect( event.getResponse() ).toHaveStatus( 200 );
            expect( event.getResponse().getData() ).toBeArray().notToBeEmpty();
        } );
    } );
} );
```


# Bundles: Group Your Tests

A Test Bundle is a CFC

TestBox relies on the fact of creating **testing bundles** which are basically CFCs. A bundle CFC will hold all the **suites** and **specs** a TestBox runner will execute and produce reports on. Don't worry, we will cover what's a suite and a spec as well. Usually they will have a name that ends with `*Spec` or `*Test.`

{% code title="tests/specs/MySpec.cfc" %}

```cfscript
component extends="testbox.system.BaseSpec"{

     // executes before all suites
     function beforeAll(){}

     // executes after all suites
     function afterAll(){}

     // All suites go in here
     function run( testResults, testBox ){

     }

}
```

{% endcode %}

This bundle CFC can contain 2 life-cycle functions and a single `run()` function where you will write your test **suites** and **specs.**

### Life-Cycle Methods

The `beforeAll()` and `afterAll()` methods are called life-cycle methods. They will execute once before the `run()` function and once after the `run()` function. This is a great way to do any global setup or tear down in your tests.

```cfscript
// executes before all suites
function beforeAll(){}

// executes after all suites
function afterAll(){}
```

### Execution

The `run()` function receives the TestBox `testResults` object as a reference and `testbox` as a reference as well. This way you can have metadata and access to what will be reported to users in a reporter. You can also use it to decorate the results or store much more information that reports can pick up later. You also have access to the `testbox` class so you can see how the test is supposed to execute, what labels was it passed, directories, options, etc.

```cfscript
function run( testResults, testBox ){

}
```


# Suites: Describe Your Tests

Describe(), Feature(), Scenario(), Given(), When()

A test suite in TestBox is a collection of specifications that model what you want to test. As we will investigate, the way the suite is expressed can be of many different types.

> Test suite is a container that has a set of tests which helps testers in executing and reporting the test execution status.

A test suite begins with a call to our TestBox `describe()` function with at least two arguments: a `title` and a `body` function/closure. The `title` is the name of the suite to register and the `body` function/closure is the block of code that implements the suite.

When applying BDD to your tests, this function is used to describe your story scenarios that you will implement.

```javascript
function run( testResults, testBox ){

     describe("A suite", function(){
          it("contains spec with an awesome expectation", function(){
               expect( true ).toBeTrue();
          });
          it("contains spec with a failure expectation", function(){
               expect( true ).toBeFalse();
          });
     });

}
```

{% hint style="success" %}
The `describe()` function is also aliased with the following names:`story(), feature(), scenario(), given(), when()`
{% endhint %}

## Arguments

There are more arguments, which you can see below:

<table data-header-hidden><thead><tr><th>Argument</th><th width="128">Required</th><th width="90">Default</th><th width="127">Type</th><th>Description</th></tr></thead><tbody><tr><td>Argument</td><td>Required</td><td>Default</td><td>Type</td><td>Description</td></tr><tr><td><code>title</code></td><td>true</td><td>---</td><td>string</td><td>The title of the suite to register</td></tr><tr><td><code>body</code></td><td>true</td><td>---</td><td>closure/udf</td><td>The closure that represents the test suite</td></tr><tr><td><code>labels</code></td><td>false</td><td>---</td><td>string/array</td><td>The list or array of labels this suite group belongs to</td></tr><tr><td><code>asyncAll</code></td><td>false</td><td>false</td><td>Boolean</td><td>If you want to parallelize the execution of the defined specs in this suite group.</td></tr><tr><td><code>skip</code></td><td>false</td><td>false</td><td>Boolean</td><td>A flag or a closure that tells TestBox to skip this suite group from testing if true. If this is a closure it must return boolean.</td></tr></tbody></table>


# Dynamic Suites

With TestBox's BDD syntax, it is possible to create suites dynamically; however, there are a few things to be aware of.

Setup for *dynamic* suites must be done in the pseudo-constructor (versus in `beforeAll()`). This is because `variables`-scoped variables set in `beforeAll()` are not available in the `describe` closure (even though they *are* available in `it` closures). This behavior can be explained by the execution sequence of a BDD bundle: When the bundle's `run()` method is called, it *collects* preliminary test data via `describe`s. *After* preliminary test data are collected, the `beforeAll()` runs, followed by the `describe` closures.

Additionally, care must be taken to pass data into the `it` closures, otherwise strange behavior will result (the values from the last loop iteration will be repeated in the body of each looped `it`).

## Example

The following bundle creates suites dynamically, by looping over test metadata.

```javascript
component
    extends="testbox.system.BaseSpec"
    hint="This is an example of a TestBox BDD test bundle containing dynamically-defined suites."
{

    /*
    * Need to do config for *dynamic* test suites here, in the
    * pseudo-constructor, versus in `beforeAll()`.
    */
    doDynamicSuiteConfig();

    /*
    * @hint This method is arbitrarily named, but it sets up 
    * metadata needed by the dynamic suites example. The setup
    * could have been done straight in the pseudo-constructor,
    * but it might be nice to organize it into such a method
    * as this.
    */
    function doDynamicSuiteConfig(){
        variables.dynamicSuiteConfig = ["foo","bar","baz"];
    }

    function run( testResults, testBox ){

        /*
        * @hint Dynamic Test Suites Example
        */
        // loop over test metadata
        for ( var thing in dynamicSuiteConfig ) {
            describe("Dynamic Suite #thing#", function(){
                // notice how data is passed into the it() closure:
                //  * data={ keyA=valueA, keyB=ValueB }
                //  * function( data )
                it( title=thing & "test", 
                    data={ thing=thing }, 
                    body=function( data ) {
                      var thing = data.thing;
                      expect( thing ).toBe( thing );
                });
            });
        }

    }

}
```


# Specs

A spec is a declaration that will usually test your system with a requirement. They are defined by calling the TestBox `it()` global function, which takes in a `title` and a `body` function/closure. The `title` is the title of this spec you will write and the `body` function/closure is a block of code that represents the spec.

A spec will contain most likely one or more expectations that will test the state of the [SUT](http://en.wikipedia.org/wiki/System_under_test) (software under test) or sometimes referred to as code under test. In BDD style, your specifications are what is used to validate your requirements of a scenario which is your `describe()` block of your [story](http://en.wikipedia.org/wiki/User_story).

```javascript
function run(){

     describe("A suite", function(){
          it("contains spec with an awesome expectation", function(){
               expect( true ).toBeTrue();
          });

          it("contains a spec with more than 1 expectation", function(){
               expect( [1,2,3] ).toBeArray();
               expect( [1,2,3] ).toHaveLength( 3 );
          });
     });

}
```

An expectation is a nice assertion DSL that TestBox exposes so you can pretty much read what should happen in the testing scenario. A spec will pass if all expectations pass. A spec with one or more expectations that fail will fail the entire spec.

{% hint style="success" %}
The `it()` function is also aliased as `then()` - except `it()` has `title` when `then()` uses `then` instead
{% endhint %}

### Arguments

| Argument | Required | Default | Type         | Description                                                                                                                                                                         |
| -------- | -------- | ------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| title    | true     | ---     | string       | the title of the spec                                                                                                                                                               |
| body     | true     | ---     | closure/udf  | The closure that represents the spec                                                                                                                                                |
| labels   | false    | ---     | string/array | The list or array of labels this suite group belongs to                                                                                                                             |
| skip     | false    | false   | Boolean      | A flag or a closure that tells TestBox to skip this suite group from testing if true. If this is a closure it must return boolean.                                                  |
| data     | false    | `{}`    | struct       | A struct of data you can bind the spec with so you can use within the `body` closure                                                                                                |
| retries  | false    | `0`     | numeric      | How many extra times to run the spec when it fails or errors. `0` inherits the bundle `retries` annotation or the global `retries` option. See [Retries](/browser-testing/retries). |

## Retrying Flaky Specs

A spec that depends on the outside world, such as a browser, a remote API or a slow server, can pass the `retries` argument to run again, up to that many extra times, before TestBox reports it. The `beforeEach()` and `afterEach()` closures run again on every attempt, and the spec stats record the `attempts`.

{% tabs %}
{% tab title="BoxLang" %}

```java
it( title = "charges a card in the sandbox", body = () => {
    expect( gateway.charge( 100 ).status ).toBe( "succeeded" )
}, retries = 2 )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
it( title = "charges a card in the sandbox", body = function(){
    expect( gateway.charge( 100 ).status ).toBe( "succeeded" );
}, retries = 2 );
```

{% endtab %}
{% endtabs %}

Retries can also be set for a whole bundle or run. See [Retries](/browser-testing/retries) for the precedence rules.

## Attaching Files

Call `attach( path, type, name )` inside a spec to attach a file, such as a screenshot or a log, to its result. Reporters list it under the spec. See [Attachments](/browser-testing/attachments).

## They are closures Ma!

Since the implementations of the `describe()` and `it()` functions are closures, they can contain executable code that is necessary to implement the test. All CFML rules of scoping apply to [closures](http://help.adobe.com/en_US/ColdFusion/10.0/Developing/WSe61e35da8d31851842acbba1353e848b35-8000.html), so please remember them. We recommend always using the `variables` scope for easy access and distinction.

```javascript
function run(){

     describe("A suite is a closure", function(){
          c = new Calculator();

          it("and so is a spec", function(){
               expect( c ).toBeTypeOf( 'component' );
          });
     });

}
```

## Spec Data Binding

The `data` argument can be used to pass in a structure of data into the spec so it can be used later within the body closure. This is great when doing looping and creating dynamic closure calls:

```javascript
// Simple Example
it( title="can handle binding", body=function( data ){
    expect(    data.keep ).toBeTrue();
}, data={ keep = true } );

// Complex Example. Let's iterate over a bunch of files and create dynamic specs
for( var filePath in files ){

  it( 
    title="#getFileFromPath( filePath )# should be valid JSON", 
    // pass in a struct of data to the spec for later evaluation
    data={ filePath = filePath },
    // the spec closure accepts the data for later evaluation
    body=function( data ) {
      var json = fileRead( data.filePath );
      var isItJson = isJSON( json );

      expect( json ).notToBeEmpty();
      expect( isItJson ).toBeTrue();

      if( isItJson ){
          var jsonData = deserializeJSON(json);
          if( getFileFromPath( filePath ) != "index.json"){
              expect( jsonData ).toHaveKey( "name" );
              expect( jsonData ).toHaveKey( "type" );
          }
      }

  });
}
```

{% hint style="warning" %}
When using the `then()` function instead of `it()` the title argument name is `then` instead of `title` for the `it()` function
{% endhint %}


# Expectations

Expectations are self-concatenated strings that evaluate an **actual** value to an **expected** value or condition. These are initiated by the global TestBox method called `expect()` which takes in a value called the **actual** value or `expectAll()` which takes in an array or struct which will be the **actual** value. It is concatenated in our expectations DSL with a matcher function that will most likely take in an expected value or condition to test. You can also concatenate the matchers and do multiple evaluations on a single actual value.

## Matchers

Each matcher implements a comparison or evaluation of the **actual** value and an **expected** value or condition. It is responsible for either passing or failing this evaluation and reporting it to TestBox. Each matcher also has a negative counterpart assertion by just prefixing the call to the matcher with a `not` expression.

```javascript
function run(){

     describe("The 'toBe' matcher evaluates equality", function(){
          it("and has a positive case", function(){
               expect( true ).toBe( true );
          });

          it("and has a negative case", function(){
               expect( false ).notToBe( true );
          });
     });

     describe("Collection expectations", function(){
        it( "can be done easily with TestBox", function(){
            expectAll( {a:2,b:4,c:6} ).toSatisfy( function(x){ return 0 == x%2; });
        });
    });

}
```

### Included Matchers

TestBox has a plethora (That's Right! I said [Plethora](http://www.merriam-webster.com/dictionary/plethora)) of matchers that are included in TestBox. The best way to see all the latest matchers is to visit our [API](http://apidocs.ortussolutions.com/testbox/current) and digest the `testbox.system.Expectation` class. There is also the ability to register and write custom matchers in TestBox via our `addMatchers()` function at runtime.

```javascript
describe("Some Included TestBox Matchers:", function() {

     describe("The 'toBe' matcher", function() {
          it("works for simple values", function() {
               coldbox = 1;
               expect( coldbox )
                    .toBe( 1 )
                    .notToBe( 5 );
          });

          it("works for complex values too (arrays,structs,queries,objects)", function() {
               expect( [1,2] ).toBe( [1,2] );
               expect( { name="luis", awesome=true} ).toBe( { awesome=true, name="luis" } );
               expect( this ).toBe( this );
               expect( queryNew("") ).toBe( queryNew("") );
          });
     });

     it("The 'toBeWithCase' matches strings with case equality", function() {
          expect( 'hello' )
               .toBeWithCase( 'hello' )
               .notToBeWithCase( 'HELLO' );
     });

     it("The 'toBeTrue' and 'toBeFalse' matchers are used for boolean operations", function() {
          coldbox_rocks = true;
          expect( coldbox_rocks ).toBeTrue();
          expect( !coldbox_rocks ).toBeFalse();
     });

     it("The 'toBeNull' expects null values", function() {
          foo = "bar";
          expect( javaCast("null", "") ).toBeNull();
          expect( foo ).notToBeNull();
     });

     it("The 'toBeInstanceOf' expects the object to be of the same class or inheritance or implementation", function() {
          expect( new coldbox.system.Assertions ).toBeInstanceOf( 'coldbox.system.Assertions' );
          expect( this ).notToBeInstanceOf( 'coldbox.system.MockBox' );
     });

     it("The 'toMatch' matcher is for regular expressions with case sensitivity", function() {
          message = 'foo man choo';

          expect( message )
               .toMatch( '^foo' )
               .toMatch( '(man)' )
               .notToMatch( 'superman' );
     });

     it("The 'toMatchNoCase' matcher is for regular expressions with no case sensitivity", function() {
          message = 'foo man choo';

          expect( message )
               .toMatchNoCase( '^FOO' )
               .toMatchNoCase( '(MAN)' )
               .notToMatchNoCase( 'SuperMan' );
     });

     describe("The 'toBeTypeOf' matcher evaluates using the CF isValid() function", function() {
          it("works with direct calls", function() {
               expect( [1,2] ).toBeTypeOf( 'Array' );
               expect( { name="luis", awesome=true} ).toBeTypeOf( 'struct' );
               expect( this ).toBeTypeOf( 'component' );
               expect( '03/01/1990' ).toBeTypeOf( 'usdate' );
          });

          it("works with dynamic calls as well", function() {
               expect( [1,2] ).toBeArray();
               expect( { name="luis", awesome=true} ).toBeStruct();
               expect( this ).toBeComponent();
               expect( '03/01/1990' ).toBeUsDate();
          });
     });

     it("The 'toBeEmpty' checks emptyness of simple or complex values", function() {
          expect( [] ).toBeEmpty();
          expect( { name="luis", awesome=true} ).notToBeEmpty();
          expect( '' ).toBeEmpty();
     });

     it("The 'toHaveLength' checks size of simple or complex values", function() {
          expect( [] ).toHaveLength( 0 );
          expect( { name="luis", awesome=true} ).toHaveLength( 2 );
          expect( 'Hello' ).toHaveLength( 5 );
     });

     it("The 'toHaveKey' checks for existence of keys in structs", function() {
          expect( { name="luis", awesome=true} ).toHaveKey( 'name' );
     });

     it("The 'toHaveDeepKey' checks for existence of keys anywhere in structs", function() {
          expect( { name="luis", { age=35, awesome=true } } ).toHaveDeepKey( 'age' );
     });

     it("The 'toThrow' checks if the actual call fails", function() {
          expect( function(){
               new calculator().divide( 40, 0 );
          }).toThrow();

          expect( function(){
               new calculator().divide( 40, 0 );
          }).toThrow( regex="zero" );
     });

});
```

### Custom Matchers

You can also build and register custom matchers. Please visit the Custom Matchers chapter to read more about [custom matchers](/digging-deeper/expectations/custom-matchers).


# Suite Groups

As we have seen before, the `describe()` function describes a test suite of related specs in a test bundle CFC. The title of the suite is concatenated with the title of a spec to create a full spec's name which is very descriptive. If you name them well, they will read out as full sentences as defined by [BDD](http://en.wikipedia.org/wiki/Behavior-driven_development) style.

```javascript
describe("A spec", function() {
     it("is just a closure, so it can contain any code", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });

     it("can have more than one expectation", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
          expect( coldbox ).toBeTrue();
     });
});
```

## Nesting describe Blocks

Calls to our `describe()` function can be nested with specs at any level or point of execution. This allows you to create your tests as a related tree of nested functions. Please note that before a spec is executed, TestBox walks down the tree executing each `beforeEach()` and `afterEach()` function in the declared order. This is a great way to logically group specs in any level as you see fit.

```javascript
describe("A spec", function() {

     beforeEach(function( currentSpec ) {
          coldbox = 22;
          application.wirebox = new coldbox.system.ioc.Injector();
     });

     afterEach(function( currentSpec ) {
          coldbox = 0;
          structDelete( application, "wirebox" );
     });

     it("is just a function, so it can contain any code", function() {
          expect( coldbox ).toBe( 22 );
     });

     it("can have more than one expectation and talk to scopes", function() {
          expect( coldbox ).toBe( 22 );
          expect( application.wirebox.getInstance( 'MyService' ) ).toBeComponent();
     });

     describe("nested inside a second describe", function() {

          beforeEach(function( currentSpec ) {
               awesome = 22;
          });

          afterEach(function( currentSpec ) {
               awesome = 22 + 8;
          });

          it("can reference both scopes as needed ", function() {
            expect( coldbox ).toBe( awesome );
          });
     });

     it("can be declared after nested suites and have access to nested variables", function() {
          expect( awesome ).toBe( 30 );
     });

});
```


# Given-When-Then Blocks

[Given-When-Then](http://martinfowler.com/bliki/GivenWhenThen.html) is a style of writing tests where you describe the state of the code you want to test (`Given`), the behavior you want to test (`When`) and the expected outcome (`Then`). (See [Specification By Example](http://martinfowler.com/bliki/SpecificationByExample.html))

Testbox supports the use of function names `given()` and `when()` in-place of `describe()` function calls. The `then()` function call is an alternative for `it()` function calls. The advantage of this style of [behavioural specifications](https://en.wikipedia.org/wiki/Behavior-driven_development#Behavioural_specifications) is that you can gather your requirements and write your tests in a common language that can be understood by developers and stake-holders alike. This common language format is often referred to as the [Gherkin](https://github.com/cucumber/cucumber/wiki/Gherkin) language; using it we can gather and document the requirements as:

```
Feature: Box Size
    In order to know what size box I need
    As a distribution manager
    I want to know the volume of the box

    Scenario: Get box volume
        Given I have entered a width of 20
        And a height of 30
        And a depth of 40
        When I run the calculation
        Then the result should be 24000
```

TestBox provides you with `feature()`, `scenario()` and `story()` wrappers for `describe()` blocks. As such we can write our requirements in test form like so:

```javascript
feature( "Box Size", function(){

    describe( "In order to know what size box I need
              As a distribution manager
              I want to know the volume of the box", function(){

        scenario( "Get box volume", function(){
            given( "I have entered a width of 20
                And a height of 30
                And a depth of 40", function(){
                when( "I run the calculation", function(){
                      then( "the result should be 24000", function(){
                          // call the method with the arguments and test the outcome
                          expect( myObject.myFunction(20,30,40) ).toBe( 24000 );
                      });
                 });
            });
        });
    });
});
```

The output from running the test will read as the original requirements, providing you with not only automated tests but also a living document of the requirements in a business-readable format.

If you prefer to gather requirements as [User Stories](https://en.wikipedia.org/wiki/User_story) then you may prefer to take advantage of the `story()` wrapper for `describe()` instead.

```javascript
story("As a distribution manager, I want to know the volume of the box I need", function() {
    given("I have a width of 20
        And a height of 30
        And a depth of 40", function() {
        when("I run the calculation", function() {
              then("the result should be 24000", function() {
                  // call the method with the arguments and test the outcome
                  expect(myObject.myFunction(20,30,40)).toBe(24000);
              });
         });
    });
});
```

As `feature()`, `scenario()` and `story()` are wrappers for `describe()` you can intermix them so that your can create tests which read as the business requirements. As with `describe()`, they can be nested to build up blocks.


# Life-Cycle Methods

## Global Callbacks <a href="#global-callbacks" id="global-callbacks"></a>

Global callbacks affect the execution of the entire test bundle CFC and all of its suites and specs.

### beforeAll() <a href="#beforeall" id="beforeall"></a>

Executes **once** before all specs for the **entire** test bundle CFC. A great place to initialize the environment the bundle needs for testing.

```cfscript
component{

	function beforeAll(){
		ORMSessionClear();
		structClear( request );  
		
		// Prepare jwt driver to use cache instead of db for easier mocking
		variables.jwt.getSettings().jwt.tokenStorage.driver = "cachebox";
		variables.jwt.getSettings().jwt.tokenStorage.properties = { cacheName : "default" };

		// Logout just in case
		variables.securityService.logout(); 
	}

}
```

### afterAll() <a href="#afterall" id="afterall"></a>

Executes **once** after all specs for the **entire** test bundle CFC. A great place to teardown the environment the bundle needed for testing.

Copy

```cfscript
component{

	function afterAll(){
		variables.securityService.logout();
		directoryDelete( "/tests/tmp", true );
	}

}
```

### run( testResults, testBox ) <a href="#run-testresults-testbox" id="run-testresults-testbox"></a>

Executes **once** so it can capture all your `describe` and `it` blocks so they can be executed by a TestBox runner.

```cfscript
function run( testResults, testbox ){

    describe("A Spec", function(){
    
    });

}
```

{% hint style="info" %}
You can find the API docs for `testbox` and the `testResults` arguments here: <https://s3.amazonaws.com/apidocs.ortussolutions.com/testbox/current/>
{% endhint %}

## Suite CallBacks

The following callbacks influence the execution of specification methods: `it(), then()`. The great flexibility of the BDD approach is that it allows you to nest `describe`, `feature`, `story`, `given`, `scenario`, `when` suite blocks to create very human readable and organized documentation for your tests. Each suite block can have its own life-cycle methods as well. Not only that, if they are nested, TestBox will walk the tree and call each `beforeEach()` and `afterEach()` in the order you declare them.

{% hint style="info" %}
TestBox will walk down the tree (from the outermost suite) for `beforeEach()` operations and out of the tree (from the innermost suite) for `afterEach()` operations.
{% endhint %}

### beforeEach( body, data ) <a href="#beforeeach-body-data" id="beforeeach-body-data"></a>

Executes before **every** single spec in a single suite block and receives the currently executing spec and any [data you want to bind the specification](https://testbox.ortusbooks.com/primers/testbox-bdd-primer/specs#spec-data-binding) with. The `body` is a closure/lambda that will fire and the `data` argument is a way to [bind the life-cycle method ](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#life-cycle-data-binding)with a struct of data that can flow down to specs.

The `body` closure will receive have the following signature:

```cfscript
function( currentSpec, data ){

}

(currentSpec, data ) => {}
```

### afterEach( body, data ) <a href="#aftereach-body-data" id="aftereach-body-data"></a>

Executes after **every** single spec in a single suite block and receives the currently executing spec and any [data you want to bind the specification](https://testbox.ortusbooks.com/primers/testbox-bdd-primer/specs#spec-data-binding) with. The `body` is a closure/lambda that will fire and the `data` argument is a way to [bind the life-cycle method ](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#life-cycle-data-binding)with a struct of data that can flow down to specs.

The `body` closure will receive have the following signature:

```cfscript
function( currentSpec, data ){

}

(currentSpec, data ) => {}
```

Here are some examples:

```cfscript
component{

     function run( testResults, testBox ){
          describe("A Spec", function(){

               beforeEach( function( currentSpec, data ){
                    // before each spec in this suite
               });

               afterEach( function( currentSpec, data ){
                    // after each spec in this suite
               });

               describe("A nested suite", function(){

                    // my parent's aroundEach()

                    beforeEach( ( currentSpec, data ) => {
                         // before each spec in this suite + my parent's beforeEach()
                    });

                    afterEach( ( currentSpec, data ) => {
                         // after each spec in this suite + my parent's afterEach()
                    });

                });

          });

          describe("A second spec", function(){

               beforeEach( function( currentSpec, data ){
                    // before each spec in this suite, separate from the two other ones
               });

               afterEach( function( currentSpec, data ){
                    // after each spec in this suite, separate from the two other ones
               });

          });
     }
}
```

### aroundEach( body, data ) <a href="#aroundeach-body-data" id="aroundeach-body-data"></a>

Executes **around** the executing spec so you can provide code that will surround the execution of the spec. It's like combining `before` and `after` in a single operation. The `body` is a closure/lambda that will fire and the `data` argument is a way to [bind the life-cycle method ](https://testbox.ortusbooks.com/in-depth/life-cycle-methods/bdd#life-cycle-data-binding)with a struct of data that can flow down to specs. This is the only way you can use CFML constructs that wrap around code like: try/catch, transaction, for, while, etc.

The `body` closure will receive have the following signature:

```cfscript
function( spec, suite, data ){

}

(spec, suite, data) => {}
```

The `spec` is the currently executing specification, the `suite` is the suite this life-cycle is embedded in and `data` is the data binding, if any.

Here is an example:

```cfscript
component{

     function run( testResults, testBox ){
          describe("A Spec", function(){

               aroundEach( function( spec, suite, data ){
                    ormClearSession();
               			ormCloseSession();
               			try {
               					// Make sure we always rollback
               					transaction {
               						arguments.spec.body();
               					}
               			} catch ( any e ) {
               					transactionRollback();
               					rethrow;
               			}
               });

               describe("A nested suite", function(){

                    // my parent's aroundEach()

                    beforeEach( function( currentSpec, data ){
                         // before each spec in this suite + my parent's beforeEach()
                    });

                    afterEach( function( currentSpec, data ){
                         // after each spec in this suite + my parent's afterEach()
                    });

                });

          });
     }
}
```

## Lifecycle Nesting Order

When you use `beforeEach()`, `afterEach()`, and `aroundEach()` at the same time, there is a specific order they fire in. For a given describe block, they will fire in this order. Remember, `aroundEach()` is split into two parts-- the half of the method before you call `spec.body()` and the second half of the method.

1. beforeEach
2. aroundEach (first half)
3. it() (the `spec.body()` call)
4. aroundEach (second half)
5. afterEach()

Here's an example:

```javascript
describe( 'my describe', function(){
	
    beforeEach( function( currentSpec ){
        // I run first
    } );
    	 
    aroundEach( function( spec, suite ){
        // I run second
        arguments.spec.body();
        // I run fourth
    });
    
    afterEach( function( currentSpec ){
        // I run fifth
    } );
    
    it( 'my it', function(){
        // I run third
    } );
    
} );
```

If there are more than one `it()` blocks, the process repeats for each one. Steps 1, 2, 4, 5 will wrap every single `it()`.

When you nest more than one describe block inside the other, the before/around/after order is the same but drills down to the innermost describe and then bubbles back up. That means the outermost `beforeEach()` starts and we end on the outermost `afterEach()`.

Here's what an example flow would look like that had before/after/around specified in two levels of describes with a single `it()` in the inner most describe.

1. Outermost `beforeEach()` call
2. Innermost `beforeEach()` call
3. Outermost `aroundEach()` call (first half)
4. Innermost `aroundEach()` call (first half)
5. The `it()` block
6. Innermost `aroundEach()` calls (second half)
7. Outermost `aroundEach()` call (second half)
8. Innermost `afterEach()` call
9. Outermost `afterEach()` call

This works regardless of the number of levels and can obviously have many permutations, but the basic order is still the same. Before/around/after and starting at the outside working in, and back out again. This process happens for every single spec or `it()` block. This is as opposed to the `beforeAll()` and `afterAll()` method which only run once for the entire CFC regardless of how many specs there are.


# Life-Cycle Data Binding

You can pass in an argument called `data` , which is a `struct` of dynamic data, to all life-cycle methods. This is useful when creating dynamic suites and specifications. This `data` will then be passed into the executing body for each life-cycle method for you.

```javascript
beforeEach( 
    data = { mydata="luis" }, 
    body = function( currentSpec, data ){
        // The arguments.data is binded via the `data` snapshot above.
        data.myData == "luis";
    }
);
```

Here is a typical example:

```javascript
describe( "Ability to bind data to life-cycle methods", function(){

    var data = [
        "spec1",
        "spec2"
    ];

    for( var thisData in data ){
        describe( "Trying #thisData#", function(){

            beforeEach( 
                data : { myData = thisData }, 
                body : function( currentSpec, data ){
                    targetData = arguments.data.myData;
            });

            it( 
                title : "should account for life-cycle data binding", 
                data  : { myData = thisData },
                body  : function( data ){
                    expect( targetData ).toBe( data.mydata );
                }
            );

            afterEach( 
                data : { myData = thisData }, 
                body : function( currentSpec, data ){
                    targetData = arguments.data.myData;
            });
        });
    }

    for( var thisData in data ){

        describe( "Trying around life-cycles with #thisData#", function(){

            aroundEach( 
                data : { myData = thisData }, 
                body : function( spec, suite, data ){
                    targetData = arguments.data.myData;
                    arguments.spec.body( data=arguments.spec.data );
            });

            it( 
                title : "should account for life-cycle data binding", 
                data  : { myData = thisData },
                body  : function( data ){
                    expect(    targetData ).toBe( data.mydata );
            });

        });

    }
});
```


# Specs and Suite Labels

Specs and suites can be tagged with TestBox labels. Labels allow you to further categorize different specs or suites so that when a runner executes with `labels` attached, only those specs and suites will be executed; the rest will be skipped. You can alternatively choose to skip specific labels when a runner executes with `excludes` attached.

```javascript
describe(title="A spec", labels="stg,railo", body=function() {
     it("executes if its in staging or in railo", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });
});

describe("A spec", function() {
     it("is just a closure, so it can contain any code", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });

     it(title="can have more than one expectation and labels", labels="dev,stg,qa,shopping", body=function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
          expect( coldbox ).toBeTrue();
     });
});
```

## Direct Suite Name Matching

When using the `testSuites` filter (via a runner, the CLI, or `TestBox` directly), TestBox performs **direct suite name matching** at any nesting depth. This means if a suite's name exactly matches the filter value it will always be included — regardless of where it sits in the nesting hierarchy.

```javascript
// This suite will always be included when testSuites="My Integration Suite"
// even if it is nested 3 levels deep
describe("My Integration Suite", function() {
     it("runs when targeted by name", function() {
          expect( true ).toBeTrue();
     });
});
```

Targeting by name from the various runners:

```bash
# BoxLang CLI runner
./testbox/run --filter-suites="My Integration Suite"

# CommandBox CLI runner
testbox run testSuites="My Integration Suite"
```

```javascript
// Programmatically via TestBox
new testbox.system.TestBox(
    bundles    = "tests.specs",
    testSuites = "My Integration Suite"
).run();
```


# Skipping Specs and Suites

Specs and suites can be skipped from execution by prefixing certain functions with the letter `x` or by using the skip argument in each of them or by using the `skip( message, detail )` function. The reporters will show that these suites or specs were skipped from execution. The functions you can prefix are:

* `it()`
* `describe()`
* `story()`
* `given()`
* `when()`
* `then()`
* `feature()`

Here are some examples:

```javascript
xdescribe("A spec", function() {
     it("was just skipped, so I will never execute", ()=>{
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });
});

describe("A spec", function() {
     it("is just a closure, so it can contain any code", ()=>{
          coldbox = 0;
          coldbox++;
          expect( coldbox ).toBe( 1 );
     });

     xit("can have more than one expectation, but I am skipped", ()=> {
          coldbox = 0;
          coldbox++;
          expect( coldbox ).toBe( 1 );
          expect( coldbox ).toBeTrue();
     });
     
     it( "can only run on lucee", ()=>{
          if( !server.keyExists( "lucee" ) ){
               skip( "Only for lucee" );
          }
     } );
});
```

## Skipping An Entire Class

As of TestBox 7.1, a BDD test class can carry a class-level `skip` annotation, so the whole class is skipped without prefixing every `describe()` or editing your runner filters.

{% tabs %}
{% tab title="BoxLang" %}
{% code title="PaymentGatewaySpec.bx" %}

```java
/**
 * @skip
 */
class extends="testbox.system.BaseSpec"{

    function run(){
        describe( "Payment gateway", () => {
            // none of this runs while @skip is present
        } )
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="PaymentGatewayTest.cfc" %}

```cfscript
/**
 * @skip
 */
component extends="testbox.system.BaseSpec"{

    function run(){
        describe( "Payment gateway", function(){
            // none of this runs while @skip is present
        } );
    }

}
```

{% endcode %}
{% endtab %}
{% endtabs %}

You can supply a reason, which shows up in the reporters:

```java
/**
 * @skip Waiting on the sandbox credentials
 */
```

Skipped classes are reported as skipped rather than silently dropped, so your totals stay honest and the class does not quietly rot.

{% hint style="info" %}
This is the class-level equivalent of `xdescribe()`. Use it when an entire bundle is blocked on something external, and prefer the [skip argument](#skip-argument) below when the decision depends on the engine or on runtime state.
{% endhint %}

## Skip Argument

The `skip` argument can be a boolean value or a closure. If the value is **true** then the suite or spec is skipped. If the return value of the closure is **true** then the suite or spec is skipped. Using the closure approach allows you to dynamically at runtime figure out if the desired spec or suite is skipped. This is such a great way to prepare tests for different CFML engines.

```javascript
describe(title="A railo suite", body=function() {
     it("can be expected to run", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });

     it(title="can have more than one expectation and another skip closure", body=function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
          expect( coldbox ).toBeTrue();

     },skip=function(){
          return false;
     });

},skip=function(){
     return !structKeyExists( server, "railo" );
});
```

## Skip Method

You can now use the `skip( message, dteail )` method to skip any spec or suite a-la-carte instead of as an argument to the function definitions. This lets you programmatically skip certain specs and suites and pass a nice message.

```cfscript
it( "can do something", () => {
    ...
    if( condition ){
        skip( "Condition is true, skipping spec" )
    }
    ...
} )
```


# Focused Specs and Suites

Specs and suites can be focused so ONLY those suites and specs execute. You will do this by prefixing certain functions with the letter `f` or by using the `focused` argument in each of them. The reporters will show that these suites or specs where execute ONLY The functions you can prefix are:

* `it()`
* `describe()`
* `story()`
* `given()`
* `when()`
* `then()`
* `feature()`

```javascript
fstory( "A spec", function() {
     it("was just skipped, so I will never execute", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });
});

describe("A spec", function() {
     it("is just a closure, so it can contain any code", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
     });

     fit("can have more than one expectation, but I am skipped", function() {
          coldbox = 0;
          coldbox++;

          expect( coldbox ).toBe( 1 );
          expect( coldbox ).toBeTrue();
     });
});
```

{% hint style="warning" %}
Please note that if a suite is focused, then all of its children will execute.
{% endhint %}


# Spies & Mocking

Please refer to our [MockBox](/mocking/mockbox) section to take advantage of all the mocking and stubbing you can do. However, every BDD TestBundle has the following functions available to you for mocking and stubbing purposes:

* `makePublic( target, method, newName )` - Exposes private methods from objects as public methods
* `querySim( queryData )` - Simulate a query
* `getMockBox( [generationPath] )` - Get a reference to MockBox
* `createEmptyMock( [className], [object], [callLogging=true])` - Create an empty mock from a class or object
* `createMock( [className], [object], [clearMethods=false], [callLogging=true])` - Create a spy from an instance or class with call logging
* `prepareMock( object, [callLogging=true])` - Prepare an instance of an object for method spies with call logging
* `createStub( [callLogging=true], [extends], [implements])` - Create stub objects with call logging and optional inheritance trees and implementation methods
* `getProperty( target, name, [scope=variables], [defaultValue] )` - Get a property from an object in any scope


# Asynchronous Testing

As you can see from our arguments for a test suite, you can pass an `asyncAll` argument to the `describe()` blocks that will allow TestBox to execute all specs in separate threads for you concurrently.

```javascript
describe(title="A spec (with setup and tear-down)", asyncAll=true, body=function() {

     beforeEach(function() {
          coldbox = 22;
          application.wirebox = new coldbox.system.ioc.Injector();
     });

     afterEach(function() {
          coldbox = 0;
          structDelete( application, "wirebox" );
     });

     it("is just a function, so it can contain any code", function() {
          expect( coldbox ).toBe( 22 );
     });

     it("can have more than one expectation and talk to scopes", function() {
          expect( coldbox ).toBe( 22 );
          expect( application.wirebox.getInstance( 'MyService' ) ).toBeComponent();
     });
});
```

> **Caution** Once you delve into the asynchronous world you will have to make sure your tests are also thread safe (var-scoped) and provide any necessary locking.


# Running Tests

Running tests is essential of course. There are many ways to run your tests, we will see the basics here, and you can check out our [Running Tests](/getting-started/running-tests) section in our in-depth guide.

### TestBox CLI

The easiest way to run your tests is to use the TestBox CLI via the `testbox run` command. Ensure you are in the web root of your project or have configured the `box.json` to include the TestBox runner in it as shown below. If not CommandBox will try to run by convention your site + `test/runner.cfm` for you.

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/anQ6EoIQEzhWbkZz841Z/image.png" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You can also pass the runner URL via the `testbox run` command. Try out the `testbox run help` command.
{% endhint %}

Here is a simple `box.json` config that has a runner and some watcher config.

```json
"testbox":{
    "runner":"http://localhost:49616/tests/runner.cfm",
    "watchers":[
        "system/**.cfc",
        "tests/**.cfc"
    ],
    "watchDelay":"250"
}
```

{% hint style="info" %}
Check out the watcher command: `testbox watch`
{% endhint %}

### URL Runner

Every test harness also has an HTML runner you can execute. By convention the URL is

```
http://localhost{port}/tests/runner.cfm
```

This will execute ALL tests in the `tests/specs` directory for you.

### URL Spec Runner

You can also target a specific spec to execute via the URL

```
http://localhost{port}/tests/specs/MySpec.cfc
```

## Test Browser

TestBox ships with a test browser that is highly configurable to whatever URL-accessible path you want. It will then show you a test browser where you can navigate and execute not only individual tests but also directory suites.

![](https://raw.githubusercontent.com/ortus-docs/testbox-docs/master/.gitbook/assets/testbox-browser.png)


# Reporters

TestBox comes also with a nice plethora of reporters:

* **ANTJunit** : A specific variant of JUnit XML that works with the ANT junitreport task
* **Codexwiki** : Produces MediaWiki syntax for usage in Codex Wiki
* **Console** : Sends report to console
* **Doc** : Documentation-style HTML with a bundle navigation, in light and dark
* **Dot** : One dot per spec, click a dot for its details and Ask AI
* **JSON** : Builds a report into JSON
* **JUnit** : Builds a JUnit compliant report
* **Raw** : Returns the raw structure representation of the testing results
* **Simple** : The complete HTML report, failures first, with Ask AI and editor links
* **Text** : Back to the 80's with an awesome text report
* **XML** : Builds yet another XML testing report
* **Tap** : A test anything protocol reporter
* **Min** : A compact HTML view that lists only what needs attention
* **MinText** : A minimalistic view of your test reports in consoles
* **Agent** : Compact, token-efficient JSON for AI agents and automation
* **NodeJS** : User-contributed: <https://www.npmjs.com/package/testbox-runner>

The HTML reporters (Simple, Min, Dot and Doc) were rebuilt in TestBox 7.2 with light and dark themes, keyboard navigation and **Ask AI** on every failure.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-818603d285b2c6afb9b098d51cabcb9c81d66060%2Freporters-simple-failures-light.png?alt=media" alt="The Simple reporter"><figcaption><p>The Simple reporter</p></figcaption></figure>

{% content-ref url="/pages/zqxNSVtrAu3AReVnO0ZN" %}
[HTML Reporters](/digging-deeper/reporters/html-reporters)
{% endcontent-ref %}


# xUnit Tests

Unit testing is a software testing technique where individual components of a software application, known as units, are tested in isolation to ensure they work as intended. Each unit is a small application part, such as a function or method, and is tested independently from other parts. This helps identify and fix bugs early in the development process, ensures code quality, and facilitates easier maintenance and refactoring. Tools like TestBox allow developers to create and run automated unit tests, providing assertions to verify the correctness of the code.

TestBox supports **xUnit** style of testing, like in other languages, via the creation of classes and functions that denote the tests to execute. You can then evaluate the test either using [assertions](/getting-started/testbox-xunit-primer/assertions) or the [expectations](/digging-deeper/expectations) library included with TestBox.

You will start by creating a test bundle (Usually with the word `Test` in the front or back), example: `UserServiceTest` or `TestUserService`.

```cfscript
component labels="disk,os" extends="testbox.system.BaseSpec" {

	/*********************************** LIFE CYCLE Methods ***********************************/

	function beforeTests(){
		application.salvador = 1;
	}

	function afterTests(){
		structClear( application );
	}

	function setup(){
		request.foo = 1;
	}

	function teardown(){
		structDelete( request, "foo" );
	}

	/*********************************** Test Methods ***********************************/

	function testFloatingPointNumberAddition() output="false"{
		var sum = 196.4 + 196.4 + 180.8 + 196.4 + 196.4 + 180.8 + 609.6;
		// sum.toString() outputs: 1756.8000000000002
		// debug( sum );
		// $assert.isEqual( sum, 1756.8 );
	}

	function testIncludes(){
		$assert.includes( "hello", "HE" );
		$assert.includes( [ "Monday", "Tuesday" ], "monday" );
	}

	function testIncludesWithCase(){
		$assert.includesWithCase( "hello", "he" );
		$assert.includesWithCase( [ "Monday", "Tuesday" ], "Monday" );
	}

	function testnotIncludesWithCase(){
		$assert.notincludesWithCase( "hello", "aa" );
		$assert.notincludesWithCase( [ "Monday", "Tuesday" ], "monday" );
	}

	function testNotIncludes(){
		$assert.notIncludes( "hello", "what" );
		$assert.notIncludes( [ "Monday", "Tuesday" ], "Friday" );
	}

	function testIsEmpty(){
		$assert.isEmpty( [] );
		$assert.isEmpty( {} );
		$assert.isEmpty( "" );
		$assert.isEmpty( queryNew( "" ) );
	}

	function testIsNotEmpty(){
		$assert.isNotEmpty( [ 1, 2 ] );
		$assert.isNotEmpty( { name : "luis" } );
		$assert.isNotEmpty( "HelloLuis" );
		$assert.isNotEmpty(
			querySim(
				"id, name
			1 | luis"
			)
		);
	}

	function testSkipped() skip{
		$assert.fail( "This Test should fail" );
	}
```


# Test Bundles

The testing bundle CFC is actually the suite in xUnit style as it contains all the test methods you would like to test with. Usually, this CFC represents a test case for a specific software under test (SUT), whether that's a model object, service, etc. This component can have some cool annotations as well that can alter its behavior.

```cfscript
component displayName="The name of my suite" asyncAll="boolean" labels="list" skip="boolean"{

}
```

TestBox relies on the fact of creating testing bundles which are basically CFCs. A bundle CFC will hold all the tests the TestBox runner will execute and produce reports on. Thus, sometimes this test bundle is referred to as a test suite in xUnit terms.

```javascript
component displayName="My test suite" extends="testbox.system.BaseSpec"{

     // executes before all tests
     function beforeTests(){}

     // executes after all tests
     function afterTests(){}

}
```

### Bundle Annotations <a href="#bundle-annotations" id="bundle-annotations"></a>

| Argument    | Required | Default | Type        | Description                                                                                                                                                                                            |
| ----------- | -------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| displayName | false    | --      | string      | If used, this will be the name of the test suite in the reporters.                                                                                                                                     |
| asyncAll    | false    | false   | boolean     | If true, it will execute all the test methods in parallel and join at the end asynchronously.                                                                                                          |
| labels      | false    | ---     | string/list | The list of labels this test belongs to                                                                                                                                                                |
| skip        | false    | false   | boolean/udf | A boolean flag that makes the runners skip the test for execution. It can also be the name of a UDF in the same CFC that will be executed and MUST return a boolean value.                             |
| retries     | false    | 0       | numeric     | How many extra times to run a failing or erroring test of the bundle. A test `retries` annotation wins over it, and it wins over the global `retries` option. See [Retries](/browser-testing/retries). |

> **Caution** If you activate the `asyncAll` flag for asynchronous testing, you HAVE to make sure your tests are also thread safe and appropriately locked.

### &#x20;<a href="#tests" id="tests"></a>

<br>


# Life-Cycle Methods

TestBox not only provides you with global life-cycle methods but also with localized test methods. This is a great way to keep your tests DRY (Do not repeat yourself)!

* `beforeTests()` - Executes once before all tests for the entire test bundle CFC
* `afterTests()` - Executes once after all tests complete in the test bundle CFC
* `setup( currentMethod )` - Executes before every single test case and receives the name of the actual testing method
* `teardown( currentMethod )` - Executes after every single test case and receives the name of the actual testing method

```javascript
component{
     function beforeTests(){}
     function afterTests(){}

     function setup( currentMethod ){}
     function teardown( currentMethod ){}
}
```

Examples

```javascript
component displayName="TestBox xUnit suite" labels="railo,cf"{

     function setup( currentMethod ){
          application.wirebox = new coldbox.system.ioc.Injector();
          structClear( request );
     }

     function teardown( currentMethod ){
          structDelete( application, "wirebox" );
          structClear( request );
     }

     function testThrows(){
          $assert.throws(function(){
               var hello = application.wirebox.getInstance( "myINvalidService" ).run();
          });
     }

     function testNotThrows(){
          $assert.notThrows(function(){
               var hello = application.wirebox.getInstance( "MyValidService" ).run();;
          });
     }

}
```


# Test Methods

TestBox discovers test methods in your bundle CFC by applying the following discovery rules:

* Any method that has a test annotation on it
* Any public method that starts or ends with the word test

```javascript
// Via inline annotation
function shouldBeAwesome() test{}

/**
* Via comment annotation
* @test
*/
function shouldBeAwesome(){}

// via conventions
function testShouldDoThis(){}
function shouldDoThisTest(){}
```

Each test method will test the state of the SUT (software under test) or sometimes referred to as code under test. It will do so by asserting that actual values from an execution match an expected value or condition. TestBox offers an assertion library that you have available in your bundle via the injected variable $assert. You can also use our expectations library if you so desire, but that is mostly used in our BDD approach.

```javascript
function testIncludes(){
       $assert.includes( "hello", "HE" );
       $assert.includes( [ "Monday", "Tuesday" ] , "monday" );
}
```

Each test function can also have some cool annotations attached to it.

| Argument | Required | Default | Type        | Description                                                                                                                                                                                                              |
| -------- | -------- | ------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| labels   | false    | ---     | string/list | The list of labels this test belongs to                                                                                                                                                                                  |
| skip     | false    | false   | boolean/udf | A boolean flag that makes the runners skip the test for execution. It can also be the name of a UDF in the same CFC that will be executed and MUST return a boolean value.                                               |
| retries  | false    | 0       | numeric     | How many extra times to run the test when it fails or errors, with its `setup()` and `teardown()`. `0` inherits the bundle `retries` annotation or the global `retries` option. See [Retries](/browser-testing/retries). |

{% tabs %}
{% tab title="BoxLang" %}

```groovy
@retries( 2 )
function testChargesACardInTheSandbox() {
    $assert.isEqual( "succeeded", gateway.charge( 100 ).status )
}
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
function testChargesACardInTheSandbox() retries="2"{
    $assert.isEqual( "succeeded", gateway.charge( 100 ).status );
}
```

{% endtab %}
{% endtabs %}

A test method can also attach files, such as screenshots or logs, to its result with `attach( path, type, name )`. See [Attachments](/browser-testing/attachments).


# Assertions

Assertions are self-concatenated strings that evaluate an actual value to an expected value or condition. These are initiated by the global TestBox variable called $assert which contains tons of included assertion methods so you can evaluate your tests.

## Evaluators

Each assertion evaluator will compare the actual value and an expected value or condition. It is responsible for either passing or failing this evaluation and reporting it to TestBox. Each evaluator also has a negative counterpart assertion by just prefixing the call to the method with a not expression.

```javascript
      function testIncludes(){
          $assert.includes( "hello", "HE" );
          $assert.includes( [ "Monday", "Tuesday" ] , "monday" );
     }

     function testNotIncludes(){
          $assert.notIncludes( "hello", "what" );
          $assert.notIncludes( [ "Monday", "Tuesday" ] , "Friday" );
     }
```

## Included Evaluators

TestBox has a plethora (That's Right! I said Plethora) of evaluators that are included in the release. The best way to see all the latest evaluator methods is to visit our [API](http://www.coldbox.org/api) and digest the *coldbox.system.Assertion* class. There is also the ability to register and write custom assertion evaluators in TestBox via our addAssertions() function.

```javascript
component displayName="TestBox xUnit suite for CF9" labels="railo,cf"{

/*********************************** LIFE CYCLE Methods ***********************************/

     function beforeTests(){
          application.salvador = 1;
     }

     function afterTests(){
          structClear( application );
     }

     function setup(){
          request.foo = 1;
     }

     function teardown(){
          structClear( request );
     }

/*********************************** Test Methods ***********************************/

     function testIncludes(){
          $assert.includes( "hello", "HE" );
          $assert.includes( [ "Monday", "Tuesday" ] , "monday" );
     }

     function testIncludesWithCase(){
          $assert.includesWithCase( "hello", "he" );
          $assert.includesWithCase( [ "Monday", "Tuesday" ] , "Monday" );
     }

     function testnotIncludesWithCase(){
          $assert.notincludesWithCase( "hello", "aa" );
          $assert.notincludesWithCase( [ "Monday", "Tuesday" ] , "monday" );
     }

     function testNotIncludes(){
          $assert.notIncludes( "hello", "what" );
          $assert.notIncludes( [ "Monday", "Tuesday" ] , "Friday" );
     }

     function testIsEmpty(){
          $assert.isEmpty( [] );
          $assert.isEmpty( {} );
          $assert.isEmpty( "" );
          $assert.isEmpty( queryNew("") );
     }

     function testIsNotEmpty(){
          $assert.isNotEmpty( [1,2] );
          $assert.isNotEmpty( {name="luis"} );
          $assert.isNotEmpty( "HelloLuis" );
          $assert.isNotEmpty( querySim( "id, name
               1 | luis") );
     }

     function testSkipped() skip{
          $assert.fail( "This Test should fail" );
     }

     boolean function isRailo(){
          return structKeyExists( server, "railo" );
     }

     function testSkippedWithConstraint() skip="isRailo"{
          $assert.fail( "This Test should fail" );
     }

     function testFails(){
          //$assert.fail( "This Test should fail" );
     }

     function testFailsShortcut() labels="railo"{
          //fail( "This Test should fail" );
     }

     function testAssert() {
          $assert.assert( application.salvador == 1 );
     }

     function testAssertShortcut() {
          assert( application.salvador == 1 );
     }

     function testisTrue() {
          $assert.isTrue( 1 );
     }

     function testisFalse() {
          $assert.isFalse( 0 );
     }

     function testisEqual() {
          $assert.isEqual( 0, 0 );
          $assert.isEqual( "hello", "HEllO" );
          $assert.isEqual( [], [] );
          $assert.isEqual( [1,2,3, {name="hello", test="this"} ], [1,2,3, {test="this", name="hello"} ] );
     }

     function testisNotEqual() {
          $assert.isNotEqual( this, new coldbox.system.MockBox() );
          $assert.isNotEqual( "hello", "test" );
          $assert.isNotEqual( 1, 2 );
          $assert.isNotEqual( [], [1,3] );
     }

     function testisEqualWithCase() {
          $assert.isEqualWithCase( "hello", "hello" );
     }

     function testnullValue() {
          $assert.null( javaCast("null", "") );
     }

     function testNotNullValue() {
          $assert.notNull( 44 );
     }

     function testTypeOf() {
          $assert.typeOf( "array", [ 1,2 ] );
          $assert.typeOf( "boolean", false );
          $assert.typeOf( "component", this );
          $assert.typeOf( "date", now() );
          $assert.typeOf( "time", timeformat( now() ) );
          $assert.typeOf( "float", 1.1 );
          $assert.typeOf( "numeric", 1 );
          $assert.typeOf( "query", querySim( "id, name
               1 | luis") );
          $assert.typeOf( "string", "hello string" );
          $assert.typeOf( "struct", { name="luis", awesome=true } );
          $assert.typeOf( "uuid", createUUID() );
          $assert.typeOf( "url", "http://www.coldbox.org" );
     }

     function testNotTypeOf() {
          $assert.notTypeOf( "array", 1 );
          $assert.notTypeOf( "boolean", "hello" );
          $assert.notTypeOf( "component", {} );
          $assert.notTypeOf( "date", "monday" );
          $assert.notTypeOf( "time", "1");
          $assert.notTypeOf( "float", "Hello" );
          $assert.notTypeOf( "numeric", "eeww2" );
          $assert.notTypeOf( "query", [] );
          $assert.notTypeOf( "string", this );
          $assert.notTypeOf( "struct", [] );
          $assert.notTypeOf( "uuid", "123" );
          $assert.notTypeOf( "url", "coldbox" );
     }

     function testInstanceOf() {
          $assert.instanceOf( new coldbox.system.MockBox(), "coldbox.system.MockBox" );
     }

     function testNotInstanceOf() {
          $assert.notInstanceOf( this, "coldbox.system.MockBox" );
     }

     function testMatch(){
          $assert.match( "This testing is my test", "(TEST)$" );
     }

     function testMatchWithCase(){
          $assert.match( "This testing is my test", "(test)$" );
     }

     function testNotMatch(){
          $assert.notMatch( "This testing is my test", "(hello)$" );
     }

     function testKey(){
          $assert.key( {name="luis", awesome=true}, "awesome" );
     }

     function testNotKey(){
          $assert.notKey( {name="luis", awesome=true}, "test" );
     }

     function testDeepKey(){
          $assert.deepKey( {name="luis", awesome=true, parent = { age=70 } }, "age" );
     }

     function testNotDeepKey(){
          $assert.notDeepKey( {name="luis", awesome=true, parent = { age=70 } }, "luis" );
     }

     function testLengthOf(){
          $assert.lengthOf( "heelo", 5 );
          $assert.lengthOf( [1,2], 2 );
          $assert.lengthOf( {name="luis"}, 1 );
          $assert.lengthOf( querySim( "id, name
               1 | luis"), 1 );

     }

     function testNotLengthOf(){
          $assert.notLengthOf( "heelo", 3 );
          $assert.notLengthOf( [1,2], 5 );
          $assert.notLengthOf( {name="luis"}, 5 );
          $assert.notLengthOf( querySim( "id, name
               1 | luis"), 0 );

     }

     // railo 4.1+ or CF10+
      function testThrows(){
          $assert.throws(function(){
               var hello = invalidFunction();
          });
     }

      // railo 4.1+ or CF10+
     function testNotThrows(){
          $assert.notThrows(function(){
               var hello = 1;
          });
     }

/*********************************** NON-RUNNABLE Methods ***********************************/

     function nonStandardNamesWillNotRun() {
          fail( "Non-test methods should not run" );
     }

     private function privateMethodsDontRun() {
          fail( "Private method don't run" );
     }

}
```

## Grouped Assertions

A failing assertion aborts the test method, so you only see the first failure per run. `assertAll()` runs several assertion closures and reports every failure at once:

{% tabs %}
{% tab title="BoxLang" %}

```groovy
function testUserProfile(){
    var user = userService.get( 1 )

    assertAll( [
        () => $assert.isEqual( "Luis", user.getName() ),
        () => $assert.isEqual( "luis@ortussolutions.com", user.getEmail() ),
        () => $assert.isTrue( user.isActive() )
    ], "user profile" )
}
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
function testUserProfile(){
    var user = userService.get( 1 );

    assertAll( [
        function(){ return $assert.isEqual( "Luis", user.getName() ); },
        function(){ return $assert.isEqual( "luis@ortussolutions.com", user.getEmail() ); },
        function(){ return $assert.isTrue( user.isActive() ); }
    ], "user profile" );
}
```

{% endtab %}
{% endtabs %}

See [Assertions](/digging-deeper/assertions#grouped-assertions) for the full details, plus the newer `isTruthy()`, `isFalsy()`, `includesAll()`, `includesAny()` and `includesNone()` assertions.

## Custom Assertions

You can also register custom assertions within the $assert object. You will do this by reading our Custom Assertions section of our TestBox docs.


# Test and Suite Labels

Tests and suites can be tagged with TestBox labels. Labels allow you to further categorize different tests or suites so that when a runner executes with labels attached, only those tests and suites will be executed; the rest will be skipped. Labels can be applied globally to the component declaration of the test bundle suite or granularly at the test method declaration.

```javascript
component displayName="TestBox xUnit suite" labels="railo,stg,dev"{

     function setup(){
          application.wirebox = new coldbox.system.ioc.Injector();
          structClear( request );
     }

     function teardown(){
          structDelete( application, "wirebox" );
          structClear( request );
     }

     function testThrows(){
          $assert.throws(function(){
               var hello = application.wirebox.getInstance( "myINvalidService" ).run();
          });
     }

     function testNotThrows(){
          $assert.notThrows(function(){
               var hello = application.wirebox.getInstance( "MyValidService" ).run();;
          });
     }

     function testFailsShortcut() labels="dev"{
          fail( "This Test should fail when executed with labels" );
     }

}
```

## Direct Suite Name Matching

When using the `testSuites` filter (via a runner, the CLI, or `TestBox` directly), TestBox performs **direct suite name matching** at any nesting depth. This means if a suite's name exactly matches the filter value it will always be included — regardless of how deeply it is nested.

```javascript
// This suite will always be included when testSuites="My xUnit Suite"
component displayName="My xUnit Suite" {

     function testSomething(){
          $assert.isTrue( true );
     }
}
```

Targeting by name from the various runners:

```bash
# BoxLang CLI runner
./testbox/run --filter-suites="My xUnit Suite"

# CommandBox CLI runner
testbox run testSuites="My xUnit Suite"
```

```javascript
// Programmatically via TestBox
new testbox.system.TestBox(
    bundles    = "tests.specs",
    testSuites = "My xUnit Suite"
).run();
```


# Skipping Tests and Suites

Tests and suites can be skipped from execution by using the `skip` annotation in the component or function declaration or our `skip()` methods. The reporters will show that these suites or tests where skipped from execution.

### Skip Annotation

The `skip` annotation can have the following values:

* `nothing` - If you just add the annotation, we will detect it and skip the test
* `true` - Skips the test
* `false` - Does not skip the test
* `{udf_name}` - It will look for a UDF with that name, execute it and the value must evalute to boolean.

```cfscript
// Skips ALL the tests if the testEnv() returns TRUE
component displayName="TestBox xUnit suite" skip="testEnv"{

     function setup(){
          application.wirebox = new coldbox.system.ioc.Injector();
          structClear( request );
     }

     function teardown(){
          structDelete( application, "wirebox" );
          structClear( request );
     }
     
     function betaTest() skip{
          ...
     }

     function testThrows() skip="true"{
          $assert.throws(function(){
               var hello = application.wirebox.getInstance( "myINvalidService" ).run();
          });
     }

     function testNotThrows(){
          $assert.notThrows(function(){
               var hello = application.wirebox.getInstance( "MyValidService" ).run();;
          });
     }

     private boolean function testEnv(){
          return ( structKeyExists( request, "env") && request.env == "stg" ? true : false );
     }

}
```

### Skip Methods

You can also skip manually by using the `skip()` method in the `Assertion` library and also in any bundle which is inherited by the `BaseSpec` class.

#### $assert.skip( message="", detail="" )

You can use the `$assert.skip( message, detail )` method to skip any spec or suite a-la-carte instead of as an argument to the function definitions. This lets you programmatically skip certain specs and suites and pass a nice message.

```cfscript
function testThrows(){
     $assert.skip()
     $assert.throws(function(){
          var hello = application.wirebox.getInstance( "myINvalidService" ).run()
     })
}
```

#### skip( message="", detail="" )

The `BaseSpec` has this method available to you as well.

```cfscript
it( "can use a mocked stub", function(){
    
    // If conditions met, then skip
    if( !conditionsMet() ){
        skip( "conditions for execution not met" )
    }

    c = createStub().$( "getData", 4 )
    r = calc.add( 4, c.getData() )
    expect( r ).toBe( 8 )
    expect( c.$once( "getData" ) ).toBeTrue()
    
} );
```


# Spies and Mocking

Please refer to our [MockBox](/mocking/mockbox) section to take advantage of all the mocking and stubbing you can do. However, every BDD TestBundle has the following functions available to you for mocking and stubbing purposes:

* `makePublic( target, method, newName )` - Exposes private methods from objects as public methods
* `querySim( queryData )` - Simulate a query
* `getMockBox( [generationPath] )` - Get a reference to MockBox
* `createEmptyMock( [className], [object], [callLogging=true])` - Create an empty mock from a class or object
* `createMock( [className], [object], [clearMethods=false], [callLogging=true])` - Create a spy from an instance or class with call logging
* `prepareMock( object, [callLogging=true])` - Prepare an instance of an object for method spies with call logging
* `createStub( [callLogging=true], [extends], [implements])` - Create stub objects with call logging and optional inheritance trees and implementation methods
* `getProperty( target, name, [scope=variables], [defaultValue] )` - Get a property from an object in any scope


# Asynchronous-Testing

You can tag a bundle component declaration with the boolean `asyncAll` annotation and TestBox will execute all specs in separate threads for you concurrently.

```javascript
component displayName="TestBox xUnit suite" skip="testEnv" asyncAll=true{

     function setup(){
          application.wirebox = new coldbox.system.ioc.Injector();
          structClear( request );
     }

     function teardown(){
          structDelete( application, "wirebox" );
          structClear( request );
     }

     function testThrows() skip="true"{
          $assert.throws(function(){
               var hello = application.wirebox.getInstance( "myINvalidService" ).run();
          });
     }

     function testNotThrows(){
          $assert.notThrows(function(){
               var hello = application.wirebox.getInstance( "MyValidService" ).run();;
          });
     }

     private boolean function testEnv(){
          return ( structKeyExists( request, "env") && request.env == "stg" ? true : false );
     }

}
```

> **Caution** Once you delve into the asynchronous world you will have to make sure your tests are also thread safe (var-scoped) and provide any necessary locking.


# Running Tests

Running tests is essential of course. There are many ways to run your tests, we will see the basics here, and you can check out our [Running Tests](/getting-started/running-tests) section in our in-depth guide.

### TestBox CLI

The easiest way to run your tests is to use the TestBox CLI via the `testbox run` command. Ensure you are in the web root of your project or have configured the `box.json` to include the TestBox runner in it as shown below. If not CommandBox will try to run by convention your site + `test/runner.cfm` for you.

<figure><img src="https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/anQ6EoIQEzhWbkZz841Z/image.png" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You can also pass the runner URL via the `testbox run` command. Try out the `testbox run help` command.
{% endhint %}

Here is a simple `box.json` config that has a runner and some watcher config.

```json
"testbox":{
    "runner":"http://localhost:49616/tests/runner.cfm",
    "watchers":[
        "system/**.cfc",
        "tests/**.cfc"
    ],
    "watchDelay":"250"
}
```

{% hint style="info" %}
Check out the watcher command: `testbox watch`
{% endhint %}

### URL Runner

Every test harness also has an HTML runner you can execute. By convention the URL is

```
http://localhost{port}/tests/runner.cfm
```

This will execute ALL tests in the `tests/specs` directory for you.

### URL Spec Runner

You can also target a specific spec to execute via the URL

```
http://localhost{port}/tests/specs/MySpec.cfc
```

## Test Browser

TestBox ships with a test browser that is highly configurable to whatever URL-accessible path you want. It will then show you a test browser where you can navigate and execute not only individual tests but also directory suites.

![](https://raw.githubusercontent.com/ortus-docs/testbox-docs/master/.gitbook/assets/testbox-browser.png)


# Reporters

TestBox comes also with a nice plethora of reporters:

* **ANTJunit** : A specific variant of JUnit XML that works with the ANT junitreport task
* **Codexwiki** : Produces MediaWiki syntax for usage in Codex Wiki
* **Console** : Sends report to console
* **Doc** : Documentation-style HTML with a bundle navigation, in light and dark
* **Dot** : One dot per spec, click a dot for its details and Ask AI
* **JSON** : Builds a report into JSON
* **JUnit** : Builds a JUnit compliant report
* **Raw** : Returns the raw structure representation of the testing results
* **Simple** : The complete HTML report, failures first, with Ask AI and editor links
* **Text** : Back to the 80's with an awesome text report
* **XML** : Builds yet another XML testing report
* **Tap** : A test anything protocol reporter
* **Min** : A compact HTML view that lists only what needs attention
* **MinText** : A minimalistic view of your test reports for consoles
* **Agent** : Compact, token-efficient JSON for AI agents and automation
* **NodeJS** : User-contributed: <https://www.npmjs.com/package/testbox-runner>

The HTML reporters (Simple, Min, Dot and Doc) were rebuilt in TestBox 7.2 with light and dark themes, keyboard navigation and **Ask AI** on every failure.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-818603d285b2c6afb9b098d51cabcb9c81d66060%2Freporters-simple-failures-light.png?alt=media" alt="The Simple reporter"><figcaption><p>The Simple reporter</p></figcaption></figure>

{% content-ref url="/pages/zqxNSVtrAu3AReVnO0ZN" %}
[HTML Reporters](/digging-deeper/reporters/html-reporters)
{% endcontent-ref %}


# Life-Cycle Annotations

In addition to the life-cycle methods according to your style, you can make any method a life-cycle method by giving it the desired annotation in its function definition. This is especially useful for parent classes that want to hook in to the TestBox life-cycle.

* `@beforeAll` - Executes once before all specs for the entire test bundle CFC
* `@afterAll` - Executes once after all specs complete in the test bundle CFC
* `@beforeEach` - Executes before every single spec in a single describe block and receives the currently executing spec.
* `@afterEach` - Executes after every single spec in a single describe block and receives the currently executing spec.
* `@aroundEach` - Executes around the executing spec so you can provide code surrounding the spec.

Below are several examples using script notation.

**DBTestCase.cfc (parent class)**

```javascript
component extends="coldbox.system.testing.BaseTestCase"{

    /**
     * @aroundEach
     */
    function wrapInDBTransaction( spec, suite ){
        transaction action="begin" {
            try {
                arguments.spec.body();
            } catch (any e) {
                rethrow;
            } finally {
                transaction action="rollback"
            }
        }
     }
}
```

**PostsTest.cfc**

```javascript
component extends="DBTestCase"{

    /**
     * @beforeEach
     */
    function setupColdBox() {
        setup();
    }

    function run() {
        given( "I have a two posts", function(){
            when( "I visit the home page", function(){
                then( "There should be two posts on the page", function(){
                    queryExecute( "INSERT INTO posts (body) VALUES ('Test Post One')" );
                    queryExecute( "INSERT INTO posts (body) VALUES ('Test Post Two')" );

                    var event = execute( event = "main.index", renderResults = true );

                    var content = event.getCollection().cbox_rendered_content;

                    expect(content).toMatch( "Test Post One" );
                    expect(content).toMatch( "Test Post Two" );
                });
            });
        });
    }
}
```

This also helps parent classes enforce their setup methods are called by annotating the methods with `@beforeAll`. No more forgetting to call `super.beforeAll()`!

{% hint style="info" %}
You can have as many annotated methods as you would like. TestBox discovers them up the inheritance chain and calls them in reverse order.
{% endhint %}


# Assertions

TestBox supports the concept of [assertions](http://en.wikipedia.org/wiki/Assertion_\(software_development\)) to allow for validations and for legacy tests. We encourage developers to use our BDD expectations as they are more readable and fun to use (Yes, fun I said!).

The assertions are modeled in the class `testbox.system.Assertion`, so you can visit the [API](http://apidocs.ortussolutions.com/testbox/current/?testbox/system/Assertion.html) for the latest assertions available. Each test bundle will receive a variable called `$assert` which represents the assertions object.

### BoxLang Assertions

If you are running and testing with BoxLang, you will have the extra benefit of the assertions dynamic methods. This allows you to just called the method in the `Assertion` object prefixed by `assert`.

```cfscript
// Normal method
$assert.isTrue()
$assert.between()
$assert.closeTo()

// With BoxLang Dynamic Methods
assertIsTrue()
assertBetween()
assertCloseTo()
```

### Common Assertions

Here are some common assertion methods:

```javascript
all( closures, [heading] )
assert( expression, [message] )
between( actual, min, max, [message] )
closeTo(expected, actual, delta, [datePart], [message])
deepKey( target, key, [message] )
fail( [message] )
includes( target, needle, [message] )
includesAll( target, needles, [message] )
includesAny( target, needles, [message] )
includesNone( target, needles, [message] )
includesWithCase( target, needle, [message] )
instanceOf( actual, typeName, [message] )
isEmpty( target, [message] )
isEqual(expected, actual, [message])
isEqualWithCase(expected, actual, [message])
isFalse( actual, [message] )
isFalsy( actual, [message] )
isGT( actual, target, [message])
isGTE( actual, target, [message])
isLT( actual, target, [message])
isLTE( actual, target, [message])
isNotEmpty( target, [message] )
isNotEqual(expected, actual, [message])
isTrue( actual, [message] )
isTruthy( actual, [message] )
key( target, key, [message] )
lengthOf( target, length, [message] )
match( actual, regex, [message] )
matchWithCase( actual, regex, [message] )
notDeepKey( target, key, [message] )
notIncludes( target, needle, [message] )
notIncludesWithCase( target, needle, [message] )
notInstanceOf( actual, typeName, [message] )
notKey( target, key, [message] )
notLengthOf( target, length, [message] )
notMatch( actual, regex, [message] )
notNull( actual, [message] )
notThrows(target, [type], [regex], [message])
notTypeOf( type, actual, [message] )
null( actual, [message] )
skip( message, detail )
throws(target, [type], [regex], [message])
typeOf( type, actual, [message] )
```

### Truthiness

`isTrue()` and `isFalse()` require an actual boolean. `isTruthy()` and `isFalsy()` are looser, and are useful when the value under test is "something or nothing" rather than a strict boolean.

{% tabs %}
{% tab title="BoxLang" %}

```java
$assert.isTruthy( "hello" )
$assert.isTruthy( [ 1, 2 ] )

$assert.isFalsy( "" )
$assert.isFalsy( 0 )
$assert.isFalsy( [] )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
$assert.isTruthy( "hello" );
$assert.isTruthy( [ 1, 2 ] );

$assert.isFalsy( "" );
$assert.isFalsy( 0 );
$assert.isFalsy( [] );
```

{% endtab %}
{% endtabs %}

### Multiple Inclusions

`includes()` checks for one needle. These three check for several at once:

{% tabs %}
{% tab title="BoxLang" %}

```java
$assert.includesAll( roles, [ "admin", "editor" ] )
$assert.includesAny( roles, [ "admin", "superuser" ] )
$assert.includesNone( serializedUser, [ "password", "salt", "apiToken" ] )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
$assert.includesAll( roles, [ "admin", "editor" ] );
$assert.includesAny( roles, [ "admin", "superuser" ] );
$assert.includesNone( serializedUser, [ "password", "salt", "apiToken" ] );
```

{% endtab %}
{% endtabs %}

### Grouped Assertions

By default a failing assertion aborts the test, so you only ever see the first failure and fix them one run at a time. `$assert.all()` runs a set of assertion closures and reports **every** failure at once.

{% tabs %}
{% tab title="BoxLang" %}

```java
$assert.all( [
    () => $assert.isEqual( "Luis", user.getName() ),
    () => $assert.isEqual( "luis@ortussolutions.com", user.getEmail() ),
    () => $assert.isTrue( user.isActive() )
], "user profile" )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
$assert.all( [
    function(){ return $assert.isEqual( "Luis", user.getName() ); },
    function(){ return $assert.isEqual( "luis@ortussolutions.com", user.getEmail() ); },
    function(){ return $assert.isTrue( user.isActive() ); }
], "user profile" );
```

{% endtab %}
{% endtabs %}

If the name and the active flag are both wrong, both are reported:

```
user profile: 1 of 3 assertions passed
  [1] expected [Luis] but received [Alice]
  [3] expected [true] but received [false]
```

The optional second argument is a heading prepended to the failure summary.

`assertAll()` is available as a spec-level shortcut for the same thing:

{% tabs %}
{% tab title="BoxLang" %}

```java
assertAll( [
    () => $assert.isEqual( 200, response.status ),
    () => $assert.key( response, "data" )
], "response envelope" )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
assertAll( [
    function(){ return $assert.isEqual( 200, response.status ); },
    function(){ return $assert.key( response, "data" ); }
], "response envelope" );
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
Grouped assertions are the assertion-style counterpart to [collection expectations](/digging-deeper/expectations#collection-expectations). Reach for them when several independent facts about one object should all be reported together.
{% endhint %}


# Custom Assertions

TestBox comes with a plethora of assertions that cover what we believe are common scenarios. However, we recommend that you create custom assertions that meet your needs and criteria so that you can avoid duplication and have re-usability. A custom assertion function can receive any amount of arguments but it must use the `fail()` method in order to fail an assertion or just return true or void for passing.

Here is an example:

```javascript
function isAwesome( required expected ){
     return ( arguments.expected == "TestBox" ? fail( 'TestBox is always awesome' ) : true );
}
```

## Assertion Registration

You can register assertion functions in several ways within TestBox, but we always recommend that you register them inside of the `beforeTests()` or `setup()` life-cycle method blocks, so they are only inserted once.

### Inline Assertions

You can pass a structure of key/value pairs of the assertions you would like to register. The key is the name of the assertion function and the value is the closure function representation.

```javascript
function beforeTests(){

     addAssertions({
          isAwesome = function( required expected ){
               return ( arguments.expected == "TestBox" ? true : fail( 'not TestBox' ) );
          },
          isNotAwesome = function( required expected ){
               return ( arguments.expected == "TestBox" ? fail( 'TestBox is always awesome' ) : true );
          }
     });

}
```

After it is registered, then you can just use it out of the `$assert` object it got mixed into.

```javascript
function testAwesomenewss(){
  $assert.isAwesome( 'TestBox' );
}
```

### Class Assertions

You can also store a [plethora](http://en.wikipedia.org/wiki/Plethora) of assertions (Yes, I said plethora), in a class and register that as the assertions via its instantiation path. This provides much more flexibility and re-usability for your projects.

```javascript
addAssertions( "model.util.MyAssertions" );
```

You can also register more than 1 class by using a list or an array:

```javascript
addAssertions( "model.util.MyAssertions, model.util.RegexAssertions" );
addAssertions( [ "model.util.MyAssertions" , "model.util.RegexAssertions" ] );
```

Here is the custom assertions source:

```javascript
component{

     function assertIsAwesome( expected, actual ){
          return ( expected eq actual ? true : false );
     }

     function assertIsFunky( actual ){
          return ( actual gte 100 ? true : false );
     }

}
```


# Expectations

TestBox allows you to create BDD expectations with our expectations and matcher API DSL. You start by calling our `expect()` method, usually with an **actual** value you would like to test. You then concatenate the expectation of that actual value/function to a result or what we call a matcher. You can also concatenate matchers (as of v2.1.0) so you can provide multiple matching expectations to a single value.

```javascript
expect( 43 ).toBe( 42 );
expect( () => calculator.add(2,2) ).toThrow();
```

## Adding Context To Failures

When several expectations in a spec assert against similar values, a raw matcher failure such as `expected [100] to be [108]` does not tell you which one broke. `withContext()` attaches a semantic label that is prepended to the failure message.

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( order.getSubtotal() ).withContext( "subtotal" ).toBe( 100 )
expect( order.getTotal() ).withContext( "total after tax" ).toBe( 108 )

// Failure: total after tax: expected [100] to be [108]
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( order.getSubtotal() ).withContext( "subtotal" ).toBe( 100 );
expect( order.getTotal() ).withContext( "total after tax" ).toBe( 108 );

// Failure: total after tax: expected [100] to be [108]
```

{% endtab %}
{% endtabs %}

The context flows through standard matchers, negated matchers and [custom matchers](/digging-deeper/expectations/custom-matchers) alike.

{% hint style="success" %}
`withContext()` shines in loops and data-driven specs, where the same expectation runs many times and the failure message alone cannot identify the iteration.
{% endhint %}

## Collection Expectations

Instead of looping and expecting per element, you can assert against an entire array or struct at once. The matcher you chain is applied to every element, and the mode decides what has to pass.

| Mode                                 | Passes when                                          |
| ------------------------------------ | ---------------------------------------------------- |
| `expectAll( collection )`            | Every element satisfies the matcher                  |
| `expectAny( collection )`            | At least one element satisfies the matcher           |
| `expectSome( collection, min, max )` | Between `min` and `max` elements satisfy the matcher |
| `expectNone( collection )`           | No element satisfies the matcher                     |

{% tabs %}
{% tab title="BoxLang" %}

```java
// every user must have an id
expectAll( users ).toHaveKey( "id" )

// at least one order is over the free-shipping threshold
expectAny( orders ).toBeGT( 50 )

// between 2 and 5 of them are flagged
expectSome( flags, 2, 5 ).toBeTrue()

// no serialized user may carry a password
expectNone( serializedUsers ).toHaveKey( "password" )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
// every user must have an id
expectAll( users ).toHaveKey( "id" );

// at least one order is over the free-shipping threshold
expectAny( orders ).toBeGT( 50 );

// between 2 and 5 of them are flagged
expectSome( flags, 2, 5 ).toBeTrue();

// no serialized user may carry a password
expectNone( serializedUsers ).toHaveKey( "password" );
```

{% endtab %}
{% endtabs %}

Failure messages report the pass and fail counts plus per-element detail, including the array index or struct key of each failing element, so you learn which elements failed rather than only that something did.

```
expectAll: 3 of 5 elements passed
  [2] expected [null] to have key [id]
  [5] expected [null] to have key [id]
```


# Matchers

The `toBe()` matcher represents an equality matcher much how an `$assert.isEqual()` behaves. Below are several of the most common matchers available to you. However, the best way to see which ones are available is to checkout the [API Docs](http://apidocs.ortussolutions.com/testbox/current).

```javascript
toBeTrue( [message] ) :  value to true
toBeFalse( [message] ) : value to be false
toBe( expected, [message] ) : Assert something is equal to each other, no case is required
toBeWithCase( expected, [message] ) : Expects with case
toBeNull( [message] ) : Expects the value to be null
toBeInstanceOf( class, [message] ) : To be the class instance passed
toMatch( regex, [message] ) : Matches a string with no case-sensitivity
toMatchWithCase( regex, [message] ) : Matches with case-sensitivity
toBeTypeOf( type, [message] ) : Assert the type of the incoming actual data, it uses the internal ColdFusion isValid() function behind the scenes, type can be array, binary, boolean, component, date, time, float, numeric, integer, query, string, struct, url, uuid plus all the ones from isValid()
toBe{type}( [message] ) : Same as above but more readable method name. Example: .toBeStruct(), .toBeArray()
toBeEmpty( [message] ) : Tests if an array or struct or string or query is empty
toHaveKey( key, [message] ) : Tests the existence of one key in a structure or hash map
toHaveDeepKey( key, [message] ) : Assert that a given key exists in the passed in struct by searching the entire nested structure
toHaveLength( length, [message] ) : Assert the size of a given string, array, structure or query
toThrow( [type], [regex], [message] );
toBeCloseTo( expected, delta, [datepart], [message] ) : Can be used to approximate numbers or dates according to the expected and delta arguments.  For date ranges use the datepart values.
toBeBetween( min, max, [message] ) : Assert that the passed in actual number or date is between the passed in min and max values
toInclude( needle, [message] ) : Assert that the given "needle" argument exists in the incoming string or array with no case-sensitivity, needle in a haystack anyone?
toIncludeWithCase( needle, [message] ) : Assert that the given "needle" argument exists in the incoming string or array with case-sensitivity, needle in a haystack anyone?
toBeGT( target, [message] ) : Assert that the actual value is greater than the target value
toBeGTE( target, [message] ) : Assert that the actual value is greater than or equal the target value
toBeLT( target, [message] ) : Assert that the actual value is less than the target value
toBeLTE( target, [message] ) : Assert that the actual value is less than or equal the target value
toBeTruthy( [message] ) : Assert the value is truthy: not false, not zero, not an empty string, not null
toBeFalsy( [message] ) : Assert the value is falsy: false, zero, an empty string or null
toBeSameInstanceAs( expected, [message] ) : Assert both references point at the very same object instance, not merely equal values
toHaveSize( expected, [message] ) : Assert the size of an array, struct, string or query. Alias of toHaveLength() reading more naturally for collections
toThrowMatching( predicate, [message] ) : Assert an exception is thrown AND that it satisfies the passed closure/lambda predicate
toIncludeAll( needles, [message] ) : Assert the target contains every one of the passed values
toIncludeAny( needles, [message] ) : Assert the target contains at least one of the passed values
toIncludeNone( needles, [message] ) : Assert the target contains none of the passed values
```

{% hint style="info" %}
Every matcher above has a negated counterpart via the [not operator](/digging-deeper/expectations/not-operator), for example `expect( x ).notToHaveSize( 3 )`.
{% endhint %}

## Truthiness: `toBeTruthy()` and `toBeFalsy()`

`toBeTrue()` and `toBeFalse()` require an actual boolean. `toBeTruthy()` and `toBeFalsy()` are looser, and are useful when a function returns "something or nothing" rather than a strict boolean.

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( "hello" ).toBeTruthy()
expect( [ 1, 2 ] ).toBeTruthy()
expect( 1 ).toBeTruthy()

expect( "" ).toBeFalsy()
expect( 0 ).toBeFalsy()
expect( [] ).toBeFalsy()
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( "hello" ).toBeTruthy();
expect( [ 1, 2 ] ).toBeTruthy();
expect( 1 ).toBeTruthy();

expect( "" ).toBeFalsy();
expect( 0 ).toBeFalsy();
expect( [] ).toBeFalsy();
```

{% endtab %}
{% endtabs %}

## Identity: `toBeSameInstanceAs()`

`toBe()` compares values. `toBeSameInstanceAs()` compares identity, which is what you want when asserting that a singleton really is a singleton, or that a factory handed back the cached object rather than a fresh one.

{% tabs %}
{% tab title="BoxLang" %}

```java
var a = getInstance( "UserService" )
var b = getInstance( "UserService" )

expect( a ).toBeSameInstanceAs( b )      // same object in memory
expect( a ).notToBeSameInstanceAs( {} )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
var a = getInstance( "UserService" );
var b = getInstance( "UserService" );

expect( a ).toBeSameInstanceAs( b );      // same object in memory
expect( a ).notToBeSameInstanceAs( {} );
```

{% endtab %}
{% endtabs %}

## Size: `toHaveSize()`

Works on arrays, structs, strings and queries.

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( [ 1, 2, 3 ] ).toHaveSize( 3 )
expect( { a : 1, b : 2 } ).toHaveSize( 2 )
expect( "TestBox" ).toHaveSize( 7 )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( [ 1, 2, 3 ] ).toHaveSize( 3 );
expect( { a : 1, b : 2 } ).toHaveSize( 2 );
expect( "TestBox" ).toHaveSize( 7 );
```

{% endtab %}
{% endtabs %}

## Exceptions: `toThrowMatching()`

`toThrow()` matches on exception type and a message regex. `toThrowMatching()` hands you the exception so you can assert anything about it.

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( () => paymentService.charge( amount = -5 ) )
    .toThrowMatching( e => e.type == "InvalidAmount" && e.detail contains "negative" )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( function(){
    paymentService.charge( amount = -5 );
} ).toThrowMatching( function( e ){
    return e.type == "InvalidAmount" && e.detail contains "negative";
} );
```

{% endtab %}
{% endtabs %}

This is the escape hatch for exceptions whose interesting detail is not in the type or the message: a custom `extendedInfo` payload, an error code, a nested cause.

## Collections: `toIncludeAll()`, `toIncludeAny()`, `toIncludeNone()`

`toInclude()` checks for a single needle. These three check for several at once against arrays, lists and strings.

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( [ "admin", "editor", "viewer" ] ).toIncludeAll( [ "admin", "editor" ] )
expect( [ "admin", "viewer" ] ).toIncludeAny( [ "admin", "superuser" ] )
expect( [ "viewer" ] ).toIncludeNone( [ "admin", "superuser" ] )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( [ "admin", "editor", "viewer" ] ).toIncludeAll( [ "admin", "editor" ] );
expect( [ "admin", "viewer" ] ).toIncludeAny( [ "admin", "superuser" ] );
expect( [ "viewer" ] ).toIncludeNone( [ "admin", "superuser" ] );
```

{% endtab %}
{% endtabs %}

Use `toIncludeNone()` to assert the absence of things that must never leak, which reads better than chaining several negated `toInclude()` calls:

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( serializedUser ).toIncludeNone( [ "password", "salt", "apiToken" ] )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( serializedUser ).toIncludeNone( [ "password", "salt", "apiToken" ] );
```

{% endtab %}
{% endtabs %}

## Specialized Matcher Families

TestBox 7.1 adds three dedicated matcher families with their own pages:

* [Set Expectations](/digging-deeper/expectations/set-expectations) for BoxLang `Set` objects
* [Range Expectations](/digging-deeper/expectations/range-expectations) for BoxLang `Range` objects
* [Data Navigator Expectations](/digging-deeper/expectations/data-navigator) for asserting against deeply nested structures by path

TestBox 7.2 adds [Browser Matchers](/browser-testing/browser-matchers), web-first matchers for bx-playwright pages and locators such as `toSee()`, `toHaveTitle()`, `toBeVisible()` and `toHaveCount()`.


# Not Operator

You can prefix your expectation with the `not` operator to easily cause negative expectations for **any** matcher. When you read the [API Docs](http://apidocs.ortussolutions.com/testbox/2.1.0/index.html) or the source, you will find nowhere the not methods. This is because we do this dynamically by convention.

```javascript
expect( actual )
     .notToBe( 4 )
     .notToBeTrue();
     .notToBeFalse();
```


# Expecting Exceptions

Our default syntax for expecting exceptions is to use our closure approach concatenated with our `toThrow()` method in our expectations or our `throws()` method in our assertions object.

> **Info** Please always remember to pass in a closure to these methods and not the actual test call: `function(){ myObj.method();}`

**Example**

```javascript
expect( function(){ myObj.method(); } ).toThrow( [type], [regex], [message] );
$assert.throws( function(){ myObj.method; }, [type], [regex], [message] )
```

This will execute the closure in a nested `try/catch` block and make sure that it either threw an exception, threw with a type, threw with a type and a regex match of the exception message. If you are in an environment that does not support closures then you will need to create a spec testing function that either uses the `expectedException` annotation or function call:

```javascript
function testMyObj(){
     expectedException( [type], [regex], [message] );
}

function testMyObj() expectedException="[type]:[regex]"{
     // this function should produce an exception
}
```

> **Caution** Please note that the usage of the `expectedException()` method can ONLY be used while in synchronous mode. If you are running your tests in asynchronous mode, this will not work. We would recommend the closure or annotation approach instead.


# Set Expectations

Matchers for BoxLang Set objects

BoxLang ships a native `Set` type. Asserting against one with array matchers means sorting first and hoping the ordering is stable, which obscures what the test actually means. TestBox 7.1 adds a family of matchers that speak set semantics directly.

{% hint style="info" %}
These matchers require BoxLang. They are not available on Lucee or Adobe ColdFusion.
{% endhint %}

## Creating Sets

Use the `setOf()` built-in to build a set inline:

```java
var roles = setOf( "admin", "editor", "viewer" )
```

## Membership And Equality

### `toBeASet()`

Asserts the actual value is a `Set`.

```java
expect( setOf( 1, 2 ) ).toBeASet()
expect( [ 1, 2 ] ).notToBeASet()
```

### `toEqualSet()`

Asserts two sets contain the same members. Order is irrelevant, which is the whole point of a set.

```java
expect( setOf( 1, 2 ) ).toEqualSet( setOf( 2, 1 ) )
```

## Subsets And Supersets

### `toBeSubsetOf()` / `toBeSupersetOf()`

```java
expect( setOf( "admin" ) ).toBeSubsetOf( setOf( "admin", "editor" ) )
expect( setOf( "admin", "editor" ) ).toBeSupersetOf( setOf( "admin" ) )
```

Use these for permission checks, where the assertion is "the granted roles include at least these" rather than an exact match.

### `toBeDisjointFrom()`

Asserts the two sets share no members at all.

```java
expect( setOf( "read" ) ).toBeDisjointFrom( setOf( "write", "delete" ) )
```

## Set Algebra

Each of these takes the other operand and the expected result.

### `toHaveUnion()`

```java
expect( setOf( 1 ) ).toHaveUnion( setOf( 2 ), setOf( 1, 2 ) )
```

### `toHaveIntersection()`

```java
expect( setOf( 1, 2 ) ).toHaveIntersection( setOf( 2, 3 ), setOf( 2 ) )
```

### `toHaveDifference()`

Members in the actual set that are not in the other set.

```java
expect( setOf( 1, 2 ) ).toHaveDifference( setOf( 2 ), setOf( 1 ) )
```

### `toHaveSymmetricDifference()`

Members in either set but not both.

```java
expect( setOf( 1, 2 ) ).toHaveSymmetricDifference( setOf( 2, 3 ), setOf( 1, 3 ) )
```

## Negated Forms

Every matcher here has a negated counterpart: `notToBeASet()`, `notToEqualSet()`, `notToBeSubsetOf()`, `notToBeSupersetOf()`, `notToHaveUnion()`, `notToHaveIntersection()`, `notToHaveDifference()` and `notToHaveSymmetricDifference()`.

## A Real Example

```java
describe( "Menu permissions", function(){

    it( "shows only the menu items the user may reach", function(){
        var visible = menuService.visibleFor( user )
        var granted = setOf( "dashboard", "reports" )

        expect( visible ).toBeASet()
        expect( visible ).toEqualSet( granted )
        expect( visible ).toBeDisjointFrom( setOf( "admin", "billing" ) )
    } )

} )
```


# Range Expectations

Matchers for BoxLang Range objects

BoxLang has a native `Range` type covering containment, ordering, bounds, stepping and clamping. TestBox 7.1 adds matchers that assert against ranges directly instead of picking them apart into endpoints first.

{% hint style="info" %}
These matchers require BoxLang. On CFML engines they are guarded and report unsupported behavior cleanly rather than erroring.
{% endhint %}

## Creating Ranges

Ranges are built with the `..` operator and stepped with `.step( n )`. There is no `rangeNew()` built-in.

```java
var base    = 1..10
var stepped = ( 0..100 ).step( 5 )
var chars   = "a".."z"
var dates   = createDate( 2024, 1, 1 )..createDate( 2024, 1, 31 )

var openEnd   = 1..     // half bounded
var openStart = ..10    // half bounded
var open      = ..      // unbounded
```

## Containment

### `toBeRange()`

```java
expect( 1..10 ).toBeRange()
```

### `toContainValue()`

Asserts a value falls inside the range.

```java
expect( 1..10 ).toContainValue( 5 )
expect( "a".."z" ).toContainValue( "m" )
expect( dates ).toContainValue( "2024-01-15" )
```

### `toContainRange()`

Asserts an entire range fits inside another.

```java
expect( 1..10 ).toContainRange( 3..7 )
```

### `toBeInRange()`

The inverse reading of `toContainValue()`, with the value as the subject. Use whichever makes the sentence read better.

```java
expect( 8 ).toBeInRange( 1..10 )
```

### `toBeBeforeRange()` / `toBeAfterRange()`

```java
expect( 0 ).toBeBeforeRange( 1..10 )
expect( 11 ).toBeAfterRange( 1..10 )
```

## Shape And Direction

### `toBeBounded()`, `toBeUnbounded()`, `toBeHalfBounded()`

```java
expect( 1..10 ).toBeBounded()
expect( .. ).toBeUnbounded()
expect( 1.. ).toBeHalfBounded()
```

### `toBeIterable()`

A range is iterable when it can actually be walked, which an unbounded range cannot.

```java
expect( 1..10 ).toBeIterable()
```

### `toBeAscending()` / `toBeDescending()`

```java
expect( 1..10 ).toBeAscending()
expect( 10..1 ).toBeDescending()
expect( "a".."z" ).toBeAscending()
```

## Step And Clamp

### `toHaveStep()`

```java
expect( ( 0..100 ).step( 5 ) ).toHaveStep( 5 )
```

### `toClampTo()`

Asserts what the range clamps a given value to. Takes the input value and the expected clamped result.

```java
expect( 1..10 ).toClampTo( 15, 10 );   // 15 clamps down to 10
expect( 1..10 ).toClampTo( -3, 1 );    // -3 clamps up to 1
```

## Native Equivalents

These matchers sit on top of the native Range API, so the following are equivalent to the assertions above:

```java
base.contains( 5 )
base.contains( 3..7 )
stepped.getStep()          // 5
base.clamp( 15 )           // 10
```

## A Real Example

```java
describe( "Pagination window", function(){

    it( "clamps a requested page into the available range", function(){
        var pages = 1..totalPages

        expect( pages ).toBeRange()
        expect( pages ).toBeBounded()
        expect( pages ).toBeAscending()

        expect( pages ).toContainValue( currentPage )
        expect( pages ).toClampTo( 9999, totalPages )
    } )

} )
```


# Data Navigator Expectations

Assert against deeply nested data structures by path

Asserting against a deeply nested structure usually means a chain of intermediate variables and `structKeyExists()` guards before you reach the value you actually care about. The data navigator matchers collapse that into a single path expression, built on BoxLang's `dataNavigate()` built-in.

Paths are JSONPath-style expressions, supporting dot notation, array indexing, recursive descent, wildcards, slices and filters. The full syntax is listed under [Path Syntax](#path-syntax) below.

{% hint style="info" %}
These matchers require BoxLang. On CFML engines they throw `TestBox.BoxLangFeatureNotAvailable`.
{% endhint %}

The examples below all assume this structure:

```java
var data = {
    "app"   : { "name" : "TestApp", "settings" : { "debug" : true, "port" : 8080 } },
    "users" : [ { "name" : "Alice", "age" : 30 } ]
}
```

## Path Syntax

Every matcher on this page takes the same path expression, handed straight to BoxLang's `dataNavigate()`.

| Syntax            | Example                     | Matches                                  |
| ----------------- | --------------------------- | ---------------------------------------- |
| Dot notation      | `app.settings.port`         | The value at that key path               |
| Array index       | `users[1]`                  | The **first** user — indexing is 1-based |
| Recursive descent | `..name`                    | Every `name` key at any depth            |
| Wildcard, keys    | `app.settings.*`            | Every value under `settings`             |
| Wildcard, array   | `users[*].name`             | The `name` of every user                 |
| Slice             | `primes[1:3]`               | Elements 1 through 3, inclusive          |
| Open-ended slice  | `primes[2:]`                | Element 2 through the end                |
| Filter            | `users[?(@.age > 18)].name` | The `name` of every user over 18         |

{% hint style="info" %}
Array indexing is **1-based**, following the language convention rather than JSONPath's usual 0-based indexing. `users[1]` is the first element, not the second.
{% endhint %}

Filters use `@` to refer to the current element and support `==`, `!=`, `>`, `<`, `>=` and `<=`. Whitespace inside the filter is tolerated, so `[?(@.active==true)]` and `[?( @.active == true )]` are equivalent.

{% hint style="success" %}
A path that resolves to many values — anything using a wildcard, slice, recursive descent or filter — is best paired with `queryPath()`, which returns every match. `path()` and the `toHavePath*()` matchers resolve to the first match.
{% endhint %}

## Existence

### `toHavePath()`

Asserts a path resolves.

```java
expect( data ).toHavePath( "app.name" )
expect( data ).toHavePath( "app.settings.debug" )
expect( data ).toHavePath( "users[1].name" )

expect( data ).notToHavePath( "nonexistent" )
expect( data ).notToHavePath( "app.nonexistent" )
```

{% hint style="info" %}
The [browser matchers](/browser-testing/browser-matchers) also define `toHavePath()`, for the URL path of a bx-playwright page. When they are registered, as in every browser bundle, pages get the browser check and every other value still gets this Data Navigator matcher.
{% endhint %}

## Values

### `toHavePathValue()`

Asserts the value at a path equals an expected value.

```java
expect( data ).toHavePathValue( "app.name", "TestApp" )
expect( data ).toHavePathValue( "app.settings.port", 8080 )
expect( data ).toHavePathValue( "users[1].name", "Alice" )

expect( data ).notToHavePathValue( "app.name", "WrongApp" )
```

### `toHavePathType()`

Asserts the type at a path. Accepts standard types (`string`, `numeric`, `boolean`, `struct`, `array`) and the aliases `str`, `num`, `bool`, `arr`, `obj` and `map`.

```java
expect( data ).toHavePathType( "app.name", "string" )
expect( data ).toHavePathType( "app.settings.port", "numeric" )
expect( data ).toHavePathType( "app.settings", "struct" )
expect( data ).toHavePathType( "users", "array" )
expect( data ).toHavePathType( "app.settings.port", "num" );   // alias

expect( data ).notToHavePathType( "app.name", "numeric" )
```

### `toHavePathSatisfying()`

Asserts the value at a path satisfies a predicate closure, for anything equality cannot express.

```java
expect( data ).toHavePathSatisfying( "app.settings.port", port -> port > 1000 )
expect( data ).toHavePathSatisfying( "app.settings", s -> s.keyExists( "debug" ) )

expect( data ).notToHavePathSatisfying( "app.name", name -> name == "WrongName" )
```

## Chaining

### `path()`

Navigates to a path and hands back a normal `Expectation` on the value there, so you can chain any matcher you like rather than being limited to the path matchers above.

```java
expect( data ).path( "app.name" ).toBe( "TestApp" )
expect( data ).path( "app.settings.port" ).toBeGT( 8000 )
expect( data ).path( "users" ).toHaveLength( 1 )
expect( data ).path( "nonexistent" ).toBeNull()
```

### `queryPath()`

Navigates to a path and hands back an `Expectation` on an **array of every match**. This is the one to use with wildcards, slices, filters and recursive descent, where a path resolves to many values rather than one.

```java
// wildcards
expect( data ).queryPath( "users[*].name" ).toHaveLength( 1 )
expect( data ).queryPath( "users[*].name" ).toInclude( "Alice" )

// filters: only the users who pass the predicate
expect( data ).queryPath( "users[?(@.age > 18)].name" ).toInclude( "Alice" )

// recursive descent: every matching key at any depth
expect( data ).queryPath( "..name" ).toInclude( "TestApp" )

expect( data ).queryPath( "nonexistent" ).toBeEmpty()
```

Slices take an inclusive, 1-based window into an array:

```java
var primes = { "values" : [ 2, 3, 5, 7, 11 ] }

expect( primes ).queryPath( "values[1:3]" ).toHaveLength( 3 )   // 2, 3, 5
expect( primes ).queryPath( "values[4:]" ).toHaveLength( 2 )    // 7, 11
```

## A Real Example

Validating an API response is where this earns its keep:

```java
it( "returns a well-formed user payload", function(){
    var response = api.get( "/users" )

    expect( response ).toHavePathValue( "status", 200 )
    expect( response ).toHavePathType( "data.users", "array" )

    // every user has an email, nobody leaks a password
    expect( response ).queryPath( "data.users[*].email" ).notToBeEmpty()
    expect( response ).notToHavePath( "data.users[*].password" )

    // pagination is sane
    expect( response ).toHavePathSatisfying( "meta.total", t -> t >= 0 )
    expect( response ).path( "meta.page" ).toBeGTE( 1 )
} )
```


# Custom Matchers

TestBox comes with a decent amount of matchers that cover what we believe are common scenarios. However, we recommend that you create custom matchers that meet your needs and criteria so that you can avoid duplication and have re-usability.

Every custom matcher is a function and must have the following signature, with `MyMatcher` being the name of your custom matcher function:

```javascript
boolean function MyMatcher( required expectation, args={} )
```

The matcher function receives the `expectation` object and a second argument which is a structure of all the arguments with which the matcher function was called with. It must then return a **true** or a **false** depending if it passes your criteria. It will most likely use the `expectation` object to retrieve the **actual** and **isNot** values. It can also set a custom failure message on the expectation object itself by using the `message` property of the `expectation` object.

```javascript
boolean function reallyFalse( expectation, args={} ){
     expectation.message = ( structKeyExists( args, "message" ) ? args.message : "[#expectation.actual#] is not really false" );
     if( expectation.isNot )
          return ( expectation.actual eq true );
     else
          return ( expectation.actual eq false );
     }
}
```

The next step is to tell TestBox about your matcher.

## Matcher Registration

You can register matcher functions in several ways within TestBox, but we always recommend that you register them inside of the `beforeAll()` or `beforeEach()` life-cycle method blocks for performance considerations and global availability.

### Inline matchers

You can pass a structure of key\\/value pairs of the matchers you would like to register. The key is the name of the matcher function and the value is the closure function representation.

```javascript
function beforeAll(){

  addMatchers( {
       toBeAwesome : function( expectation, args={} ){ return expectation.actual gte 100; },
       toBeGreat : function( expectation, args={} ){ return expectation.actual gte 1000; },
       // please note I use positional values here, you can also use name-value arguements.
       toBeGreaterThan : function( expectation, args={} ){ return ( expectation.actual gt args[ 1 ]  ); }
  } );

}
```

After it is registered, then you can use it.

```javascript
it("A custom matcher", function(){
  expect( 100 ).toBeAwesome();
  expect( 5000 ).toBeGreat();
  expect( 10 ).toBeGreaterThan( 5 );
});
```

### Class Matchers

You can also store a [plethora](http://en.wikipedia.org/wiki/Plethora) of matchers (Yes, I said plethora), in a class and register that as the matchers via its instantiation path. This provides much more flexibility and re-usability for your projects.

```javascript
addMatchers( "model.util.MyMatchers" );
```

You can also register an instance:

```javascript
addMatchers( new models.util.MyMatchers() );
```

### Browser Matchers

TestBox ships a ready-made matcher class for bx-playwright pages and locators, `testbox.system.browser.BrowserMatchers`. Bundles with [browser support](/browser-testing/browser-testing#turning-on-browser-support) (`@browser`, `@browserProfile` or `@baseURL`) register it for you; in any other BoxLang spec, register it like any class of matchers:

```java
addMatchers( new testbox.system.browser.BrowserMatchers() )

expect( page ).toSee( "Welcome" )
expect( page.locator( ".todo" ) ).toHaveCount( 3 )
```

It requires BoxLang and the bx-playwright module. See [Browser Matchers](/browser-testing/browser-matchers).

### Failure Messages And Context

Custom matcher failures route through the same internal fail path as built-in matchers, so any [context](/digging-deeper/expectations#adding-context-to-failures) set on the expectation is applied to your matcher's message too:

{% tabs %}
{% tab title="BoxLang" %}

```java
expect( 10 ).withContext( "retry budget" ).toBeGreaterThan( 50 )
// Failure: retry budget: expected [10] to be greater than [50]
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
expect( 10 ).withContext( "retry budget" ).toBeGreaterThan( 50 );
// Failure: retry budget: expected [10] to be greater than [50]
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Fixed in TestBox 7.1:** custom matchers previously raised their failure message directly, bypassing the internal fail method. That meant `withContext()` applied to built-in matchers but was silently dropped for custom ones. Both behave the same way now.
{% endhint %}


# Output Utilities

## Tests Output Utilities

Sometimes you will need to produce output from your tests and you can do so elegantly via some functions we have provided that are available in your test bundles:

<table data-header-hidden><thead><tr><th width="254">Method</th><th>Comment</th></tr></thead><tbody><tr><td><strong>Method</strong></td><td><strong>Comment</strong></td></tr><tr><td><code>console()</code></td><td>Send output to the system console</td></tr><tr><td><code>debug()</code></td><td>Send output to the TestBox reporter debugger</td></tr><tr><td><code>clearDebugBuffer()</code></td><td>Clear the debugger</td></tr><tr><td><code>print()</code></td><td>Send output to the output buffer (could be browser or console depending on the runtime)</td></tr><tr><td><code>printLn()</code></td><td>Same as print() but with a new line separator. (Ccould be browser or console depending on the runtime)</td></tr></tbody></table>

These are great little utilities that are needed to send output to several locations from within your tests.

{% hint style="success" %}
**Hint**: Please note that the `debug()` method does NOT do deep copies by default.
{% endhint %}

```javascript
console( myResults );

debug( myData );
debug( myData, true );

debug( var=myData, top=5 );

print( "Running This Test with #params.toString()#" );
println( "Running This Test with #params.toString()#" );
```

## Request Output Utilities

Sometimes you need to dump something that is in the CFC you are testing or maybe an asynchronous test. The aforementioned methods are only accessible from your test bundle, so getting to the TestBox output utilities is not easy.

Since version 4.0 we have implemented the testing utilities into the `request` scope as `request.testbox.` Which will give you access to all the same output utilities:

| **Method**           | **Comment**                                  |
| -------------------- | -------------------------------------------- |
| `console()`          | Send output to the console                   |
| `debug()`            | Send output to the TestBox reporter debugger |
| `clearDebugBuffer()` | Clear the debugger                           |
| `print()`            | Send output to the ColdFusion output buffer  |
| `printLn()`          | Same as print() but adding a \<br> separator |

```javascript
request.testbox.console( "I am here" )
request.testbox.debug( "why is this not running" )
```


# Runner Listeners

If you are creating runners and want to tap into the runner listeners or callbacks, you can do so by creating a class or a struct with the different events we announce.

<table><thead><tr><th width="212">Event</th><th>Description</th></tr></thead><tbody><tr><td><strong>onBundleStart</strong></td><td>When each bundle begins execution</td></tr><tr><td><strong>onBundleEnd</strong></td><td>When each bundle ends execution</td></tr><tr><td><strong>onSuiteStart</strong></td><td>Before a suite (describe, story, scenario, etc)</td></tr><tr><td><strong>onSuiteEnd</strong></td><td>After a suite</td></tr><tr><td><strong>onSpecStart</strong></td><td>Before a spec (it, test, then)</td></tr><tr><td><strong>onSpecEnd</strong></td><td>After a spec</td></tr></tbody></table>

Every `run` and `runRaw` methods accepts a `callbacks` argument, which can be a Class with the right listener methods or a struct with the right closure methods. This will allow you to listen to the testing progress and get information about it. This way you can build informative reports or progress bars.

```javascript
class{

    // Called at the beginning of a test bundle cycle
    function onBundleStart( target, testResults ){
    
    }
    
    // Called at the end of the bundle testing cycle
    function onBundleEnd( target, testResults ){
    
    }
    
    // Called anytime a new suite is about to be tested
    function onSuiteStart( target, testResults, suite ){
    
    }
    
    // Called after any suite has finalized testing
    function onSuiteEnd( target, testResults, suite ){
    
    }
    
    // Called anytime a new spec is about to be tested
    function onSpecStart( target, testResults, suite, spec ){
    
    }
    
    // Called after any spec has finalized testing
    function onSpecEnd( target, testResults, suite, spec ){
    
    }
    
}
```


# Reporters

TestBox ships with a rich set of reporters for every use case:

| Reporter    | Description                                                                               |
| ----------- | ----------------------------------------------------------------------------------------- |
| `Agent`     | Compact, token-efficient JSON for AI agents and automation                                |
| `ANTJunit`  | JUnit XML variant compatible with the ANT `junitreport` task                              |
| `Codexwiki` | MediaWiki syntax for use in Codex Wiki (DEPRECATED)                                       |
| `Console`   | Sends the report to the console                                                           |
| `Doc`       | Documentation-style HTML with a bundle navigation and light and dark themes               |
| `Dot`       | One dot per spec with a details drawer and light and dark themes                          |
| `JSON`      | Full JSON report of all results                                                           |
| `JUnit`     | Standard JUnit-compliant XML report                                                       |
| `Min`       | Compact HTML view that lists only what needs attention                                    |
| `MinText`   | Minimalistic plain-text report                                                            |
| `Raw`       | Raw BoxLang/CFML struct representation of results                                         |
| `Simple`    | The complete HTML report: failures first, then every bundle, with Ask AI and editor links |
| `Tap`       | Test Anything Protocol (TAP) output (DEPRECATED)                                          |
| `Text`      | Full plain-text report                                                                    |
| `XML`       | XML-based testing report                                                                  |

To use a specific reporter, append `reporter` to your runner URL, e.g. `&reporter=Text`, or set it in your `runner.bxm` / `runner.cfm`.

## HTML Reporters

`Simple`, `Min`, `Dot` and `Doc` were rebuilt in TestBox 7.2 with light and dark themes, keyboard navigation, highlighted BoxLang and CFML code and **Ask AI** on every failure. They are fully inlined, so reports still run airgapped.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-818603d285b2c6afb9b098d51cabcb9c81d66060%2Freporters-simple-failures-light.png?alt=media" alt="The Simple reporter"><figcaption><p>The Simple reporter</p></figcaption></figure>

{% content-ref url="/pages/zqxNSVtrAu3AReVnO0ZN" %}
[HTML Reporters](/digging-deeper/reporters/html-reporters)
{% endcontent-ref %}

## `ConsoleReporter` — Hiding Skipped Tests

The `ConsoleReporter` now accepts a `hideSkipped` option (default `false`) that suppresses skipped spec output — useful when you have many pending specs and want cleaner terminal output.

```javascript
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.ConsoleReporter",
        options : { hideSkipped : true }
    }
);
```

When using the BoxLang CLI runner, pass `--show-skipped=false` instead:

```bash
./testbox/run --show-skipped=false
```

## `AgentReporter` - Token-Efficient Output for AI Agents

**Added in TestBox 7.2.** The `Agent` reporter is a compact JSON reporter for AI agents and automation. It reports the totals plus only the specs that failed or errored, as a single minified line. A passing run costs a few dozen tokens, where the `JSON` reporter returns the full result set.

{% tabs %}
{% tab title="BoxLang" %}
{% code title="Programmatic" %}

```java
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.AgentReporter",
        options : { maxFailures : 10, includeStack : true }
    }
)
println( testbox.run() )
```

{% endcode %}

{% code title="BoxLang CLI runner" %}

```bash
./testbox/run --reporter=agent
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="Programmatic" %}

```cfscript
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.AgentReporter",
        options : { maxFailures : 10, includeStack : true }
    }
);
writeOutput( testbox.run() );
```

{% endcode %}

{% code title="HTML runner URL" %}

```
runner.cfm?reporter=agent&directory=tests.specs
```

{% endcode %}
{% endtab %}
{% endtabs %}

### Output

```json
{"ok":false,"totals":{"pass":120,"fail":2,"error":1,"skipped":3,"specs":126,"ms":4210},"failures":[{"bundle":"tests.specs.FooTest","spec":"Foo > can add","status":"failed","message":"Expected [4] but received [3]","at":"tests/specs/FooTest.cfc:42"}],"truncated":0}
```

| Key         | Description                                                                                                                                                                                 |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ok`        | `true` when nothing failed or errored. Agents can branch on this alone.                                                                                                                     |
| `totals`    | `pass`, `fail`, `error`, `skipped`, `specs` and `ms` for the whole run.                                                                                                                     |
| `failures`  | One entry per failed or errored spec: `bundle`, `spec` (suite path joined with `>`), `status` (`failed` or `error`), `message` and `at` (`file:line`, relative to the web or working root). |
| `truncated` | How many failures were left out because of `maxFailures`.                                                                                                                                   |

Bundle-level exceptions, such as a failing `beforeAll()`, appear in `failures` with an empty `spec` and the `error` status.

### Options

| Option             | Default    | Description                                                                                                                             |
| ------------------ | ---------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `detail`           | `failures` | `summary` returns totals only, `failures` adds the failures, `all` also adds a compact `specs` list (`bundle`, `spec`, `status`, `ms`). |
| `maxFailures`      | `20`       | Maximum failures listed. `0` means unlimited. The overflow is reported in `truncated`.                                                  |
| `maxMessageLength` | `300`      | Truncates each failure message. `0` means unlimited.                                                                                    |
| `includeStack`     | `false`    | Adds a `stack` array of `file:line` frames to each failure, user code first.                                                            |
| `stackDepth`       | `3`        | Number of frames kept when `includeStack` is `true`.                                                                                    |
| `includeSkipped`   | `false`    | Adds a `skipped` array of spec paths.                                                                                                   |
| `includeDebug`     | `false`    | Adds a `debug` array with the `debug()` output of the run.                                                                              |

{% hint style="info" %}
The reporter does not change the process exit code. Read the `ok` key to decide whether the run passed.
{% endhint %}

## `StreamingReporter` — Real-Time SSE Output 🆕

The new `StreamingReporter` (backed by `StreamingRunner`) pushes each spec result to the client in real time via Server-Sent Events. It powers both the [TestBox RUN IDE](/getting-started/running-tests/testbox-run-ide) and the `testbox run --streaming` command.

{% content-ref url="/pages/2RZVKzZXXh182rLMwI02" %}
[Streaming Runner](/getting-started/running-tests/streaming-runner)
{% endcontent-ref %}

## Attachments and Retries

Specs can [attach files](/browser-testing/attachments), such as screenshots, traces or logs, and can be [retried](/browser-testing/retries). Reporters show both:

| Reporter            | Attachments                                                                                                             | Retries                                        |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| `JSON`, `Raw`       | An `attachments` array of `{ path, type, name }` in every spec's stats                                                  | An `attempts` count in every spec's stats      |
| `Simple`            | A linked list under each spec                                                                                           | `(passed after N attempts)` after the duration |
| `JUnit`, `ANTJunit` | A `<system-out>` with one `[[ATTACHMENT\|path]]` line per file, read by the Jenkins JUnit Attachments plugin and GitLab |                                                |
| `Text`, `Console`   | Listed under failed and errored specs                                                                                   | `(passed after N attempts)` after the duration |

See [Attachments in Reports](/browser-testing/attachments#attachments-in-reports) for an example of the JUnit output.

## Run All and Run Failed

The `Simple`, `Min`, `Dot` and `Doc` reports have a **Run All** button. When something failed or errored, a **Run Failed (N)** button sits next to it and reruns only those specs.

![The Simple report with Run All and Run Failed](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-f2c5ae3c5e503970f53bc3336288b31570e14eeb%2Ftestbox-sc-run-failed.png?alt=media)

* The link is built from the report on screen, `?testBundles=...&testSpecs=...` with the failed bundles and spec ids, so the web runner keeps no state between runs. Fix, click it again, repeat.
* When the spec ids would make the link longer than 2000 characters, it reruns the failed bundles whole.
* Bundles that failed outside of a spec, for example in `beforeAll()`, are left out: they are broken, not failed. The report shows them as bundle exceptions.
* The same list is available from code on every engine with `TestResult.getFailedTargets()`, and the BoxLang CLI runner keeps it between runs for [`--failed`](/browser-testing/running-browser-tests#rerun-what-failed-failed).

{% tabs %}
{% tab title="BoxLang" %}

```java
var results = new testbox.system.TestBox( directory = "tests.specs" ).runRaw()
var failed  = results.getFailedTargets()
// { bundles : [ "tests.specs.LoginSpec" ], specs : [ "spec id" ], bundleErrors : [] }

if ( failed.bundles.len() ) {
	new testbox.system.TestBox( bundles = failed.bundles )
		.runRaw( testBundles = failed.bundles, testSpecs = failed.specs )
}
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
var results = new testbox.system.TestBox( directory = "tests.specs" ).runRaw();
var failed  = results.getFailedTargets();

if ( arrayLen( failed.bundles ) ) {
	new testbox.system.TestBox( bundles = failed.bundles )
		.runRaw( testBundles = failed.bundles, testSpecs = failed.specs );
}
```

{% endtab %}
{% endtabs %}

## Open In Editor

The HTML reporters (`Simple`, `Min`, `Dot` and `Doc`) allow you to set a code editor of choice so they create clickable links for failures, stack traces and tag contexts, opening exceptions in your editor at the exact line.

{% hint style="info" %}
The default editor is `vscode`.
{% endhint %}

Use the `url.editor` parameter in the URL or set it in your `runner.cfm`:

```markup
<cfsetting showDebugOutput="false">
<!--- Executes all tests in the 'specs' folder with simple reporter by default --->
<cfparam name="url.reporter" 			default="simple">
<cfparam name="url.directory" 			default="tests.specs">
<cfparam name="url.recurse" 			default="true" type="boolean">
<cfparam name="url.bundles" 			default="">
<cfparam name="url.labels" 				default="">
<cfparam name="url.excludes" 			default="">
<cfparam name="url.reportpath" 			default="#expandPath( "/tests/results" )#">
<cfparam name="url.propertiesFilename" 	default="TEST.properties">
<cfparam name="url.propertiesSummary" 	default="false" type="boolean">
<cfparam name="url.editor" 				default="vscode">

<!--- Include the TestBox HTML Runner --->
<cfinclude template="/testbox/system/runners/HTMLRunner.cfm" >
```

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-14cbc65da60d8fd00283608bf7184b06bfa1df4a%2Freporters-simple-failures-dark.png?alt=media" alt="Open in editor links on every failure"><figcaption><p>Every failure has an <em>Open in editor</em> link, and every stack frame links to its file and line</p></figcaption></figure>

### Available Editors

* atom
* emacs
* espresso
* idea
* macvim
* sublime
* textmate
* vscode
* vscode-insiders

## Reporter Screenshots

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-11e1ea8257aa2319395e6e7ccdded2ae147f6cfa%2Freporters-dot-light.png?alt=media" alt="Dot reporter"><figcaption><p>Dot</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-046c4a32d5e3edad501d41d1d1f495f0b55a4232%2Freporters-doc-light.png?alt=media" alt="Doc reporter"><figcaption><p>Doc</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-7b4b06739541b4582de04478189120bedc5881e6%2Freporters-min-light.png?alt=media" alt="Min reporter"><figcaption><p>Min</p></figcaption></figure>

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/roKYX2aWFolqTbkJmRlO/testbox-sc-json.png)

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/axvUWUv273fWpXG1Wfaw/testbox-sc-junit.png)

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-818603d285b2c6afb9b098d51cabcb9c81d66060%2Freporters-simple-failures-light.png?alt=media" alt="Simple reporter"><figcaption><p>Simple</p></figcaption></figure>

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/o04GJhrEsqWUUL1pgndR/testbox-sc-text.png)

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/CuKhenLPcl8KSkaJpKHa/testbox-sc-xml.png)


# HTML Reporters

**New in TestBox 7.2.** The four HTML reporters, `Simple`, `Min`, `Dot` and `Doc`, have been rebuilt from the ground up. They keep every feature they had and add a much clearer view of what went wrong, light and dark themes, keyboard navigation, syntax highlighting for BoxLang and CFML, and **Ask AI**: hand any failure to ChatGPT, Claude or your coding agent with one click.

{% file src="/files/GuLliZQfxzx4CLiwcUlA" %}
A 50 second tour of the new HTML reporters
{% endfile %}

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-818603d285b2c6afb9b098d51cabcb9c81d66060%2Freporters-simple-failures-light.png?alt=media" alt="The Simple reporter in light mode with three failures and three errors"><figcaption><p>The Simple reporter, light mode</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-14cbc65da60d8fd00283608bf7184b06bfa1df4a%2Freporters-simple-failures-dark.png?alt=media" alt="The Simple reporter in dark mode"><figcaption><p>The same run in dark mode</p></figcaption></figure>

{% hint style="info" %}
Nothing changes in how you run them. Use `reporter=simple`, `reporter=min`, `reporter=dot` or `reporter=doc` on the runner URL or in your `runner.cfm` / `runner.bxm`, exactly as before.
{% endhint %}

## What Changed

|                   | Before                       | Now                                                              |
| ----------------- | ---------------------------- | ---------------------------------------------------------------- |
| **Look**          | Bootstrap 4 and Font Awesome | Bootstrap 5.3 with Bootstrap Icons, on the TestBox palette       |
| **Themes**        | One light theme              | Light, dark and follow-the-system, remembered between runs       |
| **Interactivity** | jQuery                       | Alpine.js, one small script                                      |
| **Code**          | SyntaxHighlighter            | Prism with BoxLang and CFML grammars and the failing line marked |
| **Page weight**   | About 1.4 MB                 | About 0.45 MB                                                    |
| **Network**       | Inlined assets               | Still inlined, reports run **airgapped**                         |
| **AI**            | None                         | Ask AI on every failure                                          |

## The Verdict First

The first thing you see in every HTML report is the verdict: a green or red banner with the totals, a proportion bar and one-click status filters. When something failed you can not miss it.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-641b6d29b60aa7fdf5bc08e7f43ae8e9c9a22ecb%2Freporters-header-dark.png?alt=media" alt="The verdict banner and the theme switch in the header"><figcaption><p>The verdict banner with the totals, the proportion bar, the status filters and the shortcuts</p></figcaption></figure>

A green run stays calm and small:

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-7971b4e70e2573f0655003bd88e4f7a5ba3a0558%2Freporters-simple-pass-light.png?alt=media" alt="A passing run"><figcaption><p>All green</p></figcaption></figure>

If a whole bundle could not run, for example because `beforeAll()` threw, the report adds a dedicated alert **above** the verdict with the exception message, so it is never hidden inside a collapsed bundle:

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-9d134c2617176224af2e9e3595d034d0c8783f8a%2Freporters-simple-exception-light.png?alt=media" alt="A bundle exception alert above the verdict"><figcaption><p>A bundle that could not run</p></figcaption></figure>

## Find Your Way Around

### Jump To The Next Failure

Press **F** to move to the next failure or error. The page scrolls to it and highlights it. The **Next failure** button in the banner does the same thing.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-c10e0773f384f934e7e76d60111d07f8d9b2984e%2Freporters-demo-next-failure.gif?alt=media" alt="Pressing F jumps from failure to failure"><figcaption><p>Press <code>F</code> to jump from failure to failure</p></figcaption></figure>

### Filter Everything

* Click a status chip (**Pass**, **Failed**, **Error**, **Skipped**) in the banner to filter the whole report. Click it again to clear it.
* Every bundle has its own status chips as well, so you can look at only the failed specs of one bundle.
* Press **/** to jump to the search box and type part of a bundle, suite or spec name.
* **Expand all** and **Collapse all** open or close every bundle. Bundles with problems start open.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-02971939352374e682daa255706495da86ac1dcb%2Freporters-demo-filter.gif?alt=media" alt="Filtering by status and by text"><figcaption><p>Status filters and live text search</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-a4ab66350203af0ee8cfa891bcd9e60c569ed499%2Freporters-filter-errors.png?alt=media" alt="Only the errors are shown"><figcaption><p>Only the errors, with a Reset filters button to get everything back</p></figcaption></figure>

### Run It Again

Every bundle, suite and spec has a **Run** link. A run link is a plain link to the runner, so the address bar always holds what you are looking at and a browser refresh runs it again. **Run All** in the header runs the full suite.

{% hint style="info" %}
A run link carries only the target you asked for (`testBundles`, `testSuites` or `testSpecs`). Every other runner option falls back to its default.
{% endhint %}

When something failed or errored, **Run Failed (N)** sits next to **Run All** and reruns only those specs. Its link lists the failed bundles and spec ids, built from the report itself, so the runner keeps no state: fix, click it again, repeat. See [Run All and Run Failed](/digging-deeper/reporters#run-all-and-run-failed).

![The Simple report with Run All and Run Failed](https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-f2c5ae3c5e503970f53bc3336288b31570e14eeb%2Ftestbox-sc-run-failed.png?alt=media)

### Open In Your Editor

Failures link to the failing file and line in your editor. See [Open In Editor](/digging-deeper/reporters#open-in-editor) for the editors you can choose.

## Light And Dark

Use the switch in the header to pick **light**, **dark** or **system**. The choice is remembered in your browser and applied before the page paints, so there is no flash of the wrong theme.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-4e6ab4462a4efcfa17c8e6458ab3a082d6abd33b%2Freporters-demo-theme.gif?alt=media" alt="Switching between light and dark"><figcaption><p>Light and dark, on the TestBox palette</p></figcaption></figure>

## Ask AI

Every failure and error has an **Ask AI** menu. It builds a prompt that contains everything a person or an assistant needs: the spec, the status, the message, the code around the failing line, the first stack frames and the exact command to run only that spec again.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b82609300f0519495566d2a7d27c1cdf28b6c9f5%2Freporters-demo-ask-ai.gif?alt=media" alt="Opening the Ask AI menu and previewing the prompt"><figcaption><p>Ask AI menu and prompt preview</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-b019babd9012a5c8ef0b1dfc1a69a2b93f095df7%2Freporters-ai-menu.png?alt=media" alt="The Ask AI menu"><figcaption><p>The Ask AI menu</p></figcaption></figure>

| Menu item                    | What it does                                                                                                                                                                     |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Copy prompt**              | Copies the prompt to the clipboard. Stays on the page and works offline.                                                                                                         |
| **Preview prompt**           | Shows exactly what would be sent, before anything leaves the page.                                                                                                               |
| **Open in ChatGPT / Claude** | Opens the provider with the prompt filled in.                                                                                                                                    |
| **Copy for a coding agent**  | Copies the failure as JSON in the [AgentReporter](/digging-deeper/reporters#agentreporter---token-efficient-output-for-ai-agents) format, for tools that read structured output. |

**Copy all failures for AI**, in the verdict banner, builds one prompt with every failure and error of the run.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-274883899b558bfdfef5c1fe63292c947b81e72d%2Freporters-ai-preview.png?alt=media" alt="The prompt preview"><figcaption><p>Preview exactly what would be sent</p></figcaption></figure>

### Your Code Stays Yours Until You Say So

The prompt is built inside the page, in your browser. Nothing is sent anywhere until you click a provider, and the first time you do, the page tells you what happens next and waits for your confirmation:

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-87695a327de18da903f65c2c0f7aa136a0b147e7%2Freporters-ai-notice.png?alt=media" alt="The first-use notice before opening a third party site"><figcaption><p>The first-use notice. Your choice is remembered in the browser.</p></figcaption></figure>

### Options

Ask AI is on by default. Configure it with reporter options:

{% tabs %}
{% tab title="BoxLang" %}
{% code title="Programmatic" %}

```java
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.SimpleReporter",
        options : {
            aiAssist       : true,
            aiContextLines : 8,
            aiStackFrames  : 5,
            aiProviders    : [
                { id : "acme", name : "Acme AI", url : "https://ai.acme.test/?p={prompt}" }
            ]
        }
    }
)
println( testbox.run() )
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="Programmatic" %}

```cfscript
var testbox = new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = {
        type    : "testbox.system.reports.SimpleReporter",
        options : {
            aiAssist       : true,
            aiContextLines : 8,
            aiStackFrames  : 5,
            aiProviders    : [
                { id : "acme", name : "Acme AI", url : "https://ai.acme.test/?p={prompt}" }
            ]
        }
    }
);
writeOutput( testbox.run() );
```

{% endcode %}
{% endtab %}
{% endtabs %}

| Option             | Default            | Description                                                                                                                                                                                                                             |
| ------------------ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aiAssist`         | `true`             | Shows the Ask AI menu. Set it to `false` to remove every Ask AI control and prompt from the page. You can also switch it off for one run with `?aiAssist=false`.                                                                        |
| `aiProviders`      | ChatGPT and Claude | An array of `{ id, name, url }`. The `url` must contain `{prompt}`, which is replaced by the URL-encoded prompt. Setting it replaces the defaults.                                                                                      |
| `aiContextLines`   | `5`                | Lines of code before and after the failing line in the prompt.                                                                                                                                                                          |
| `aiStackFrames`    | `8`                | Stack frames in the prompt. Very long prompts are trimmed automatically to fit a URL.                                                                                                                                                   |
| `aiPrompt`         | built in           | A custom prompt template, see below.                                                                                                                                                                                                    |
| `inlineImageMaxKB` | `2048`             | Image attachments, such as failure screenshots, up to this size are embedded in the page as thumbnails. Larger ones stay links. `0` links every image. See [Attachments](/browser-testing/attachments#screenshots-in-the-html-reports). |
| `urlParams`        | none               | A struct of request params, such as `editor` or `aiAssist`, for reports that you produce from code. See below.                                                                                                                          |

### Your Own Prompt

Use `aiPrompt` to ask for what your team needs. These tokens are replaced when the prompt is built:

| Token       | Replaced with                                                             |
| ----------- | ------------------------------------------------------------------------- |
| `{intro}`   | The TestBox version, the engine and a one line description of the outcome |
| `{spec}`    | The suite path and the spec name                                          |
| `{status}`  | `failed` or `error`                                                       |
| `{message}` | The failure or error message                                              |
| `{code}`    | The code around the failing line, fenced                                  |
| `{stack}`   | The first stack frames                                                    |
| `{rerun}`   | The command that runs only this spec again                                |

```java
options : {
    aiPrompt : "{intro}

Spec: {spec} ({status})
{message}

{code}

Explain the cause in two sentences and propose a fix for the code, not the test.
Run it again with: {rerun}"
}
```

### Reports Produced From Code

In a web request the reporters read `editor` and `aiAssist` from the `url` scope. When you produce a report from code, for example with the BoxLang CLI, there is no `url` scope. Pass the same values with the `urlParams` option instead:

```java
options : { urlParams : { editor : "idea", aiAssist : "false" } }
```

## The Reporters

### Simple

Failures first, then every bundle with its suites and specs. The most complete view, and the default of the runners.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-14cbc65da60d8fd00283608bf7184b06bfa1df4a%2Freporters-simple-failures-dark.png?alt=media" alt="Simple reporter"><figcaption><p>Simple: a <em>Needs attention</em> section on top, every bundle below</p></figcaption></figure>

### Min

A compact page that lists only what needs attention, one line per failure, with the verdict and bundle exceptions above it.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-7b4b06739541b4582de04478189120bedc5881e6%2Freporters-min-light.png?alt=media" alt="Min reporter"><figcaption><p>Min: one line per failure</p></figcaption></figure>

### Dot

One dot per spec, grouped by bundle. Hover a dot for its name, click it to open the details, the code and Ask AI in a drawer. Filters dim the dots that do not match, so the shape of your run stays in place.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-11e1ea8257aa2319395e6e7ccdded2ae147f6cfa%2Freporters-dot-light.png?alt=media" alt="Dot reporter"><figcaption><p>Dot: your whole run at a glance</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-42884af5a0760de99e93dda542dcecea98e4771a%2Freporters-demo-dot-drawer.gif?alt=media" alt="Clicking a failed dot opens a drawer with the details"><figcaption><p>A click on a dot opens the details in a drawer</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-7f73288f447e04624b17ff52ed46dbebd6f2d692%2Freporters-dot-drawer.png?alt=media" alt="The drawer of the Dot reporter"><figcaption><p>The drawer shows the message, the code and Ask AI</p></figcaption></figure>

### Doc

Your suite rendered like documentation: a bundle navigation on the side and every suite and spec as readable text. A good fit for BDD suites that you want to read.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-08880847e12423f8c1225c6f7d0722391003f5b9%2Freporters-doc-dark.png?alt=media" alt="Doc reporter"><figcaption><p>Doc: bundle navigation and documentation-style output</p></figcaption></figure>

## On Every Screen

The reports are responsive, so you can open a CI artifact on your phone.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-2f173fd26a36f1e353b4d2bf02036b3f0a9b03fd%2Freporters-simple-mobile.png?alt=media" alt="Simple reporter on a phone" width="320"><figcaption><p>Simple on a phone</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-577fc05ea67b5204e007edea488b7528cdeea372%2Freporters-dot-mobile.png?alt=media" alt="Dot reporter on a phone" width="320"><figcaption><p>Dot on a phone</p></figcaption></figure>

## Airgapped By Design

Everything a report needs, the styles, the icons, the scripts, the highlighter and the logo, is inlined in the page. A report is a single file that works offline, on a build server without internet, or attached to an email. The only time the page talks to the network is when you click an Ask AI provider.

Contributing to TestBox? The inlined front-end libraries (Bootstrap, Bootstrap Icons, Alpine and Prism) are built from `build/vendor` in the TestBox repository. Rebuild them with one command, and CI checks that the committed files match:

```bash
box run-script assets:update
```

{% hint style="warning" %}
**Changed in TestBox 7.2:** the `url.fullPage` switch was removed. An HTML reporter always returns a complete page. If you embedded a reporter in your own page, include the report in an `<iframe>` or use the `JSON` reporter and render the data yourself.
{% endhint %}


# Custom Reporters

How to create and use custom reporters in TestBox.

## Building Reporters

You can also build your own reporters by implementing our core interface: `testbox.system.reporters.IReport`

```javascript
interface{

  /**
  * Get the name of the reporter
  */
  function getName();

  /**
  * Do the reporting thing here using the incoming test results
  * The report should return back in whatever format they desire and should set any
  * Specifc browser types if needed.
  * @results.hint The instance of the TestBox TestResult object to build a report on
  * @testbox.hint The TestBox core object
  * @options.hint A structure of options this reporter needs to build the report with
  */
  any function runReport(
    required testbox.system.TestResult results,
    required testbox.system.TestBox testbox,
    struct options={} );
}
```

## Executing Your Reporter

Once you implement your own report you just need to pass the class path or the instance of your reporter to the TestBox runner methods using the `reporter` argument. The `reporter` argument can be the following values:

* `string` - The class path of your reporter
* `instance` - The instance of your reporter CFC
* `struct` - A structure representing your reporter with the following keys: `{ type="class_path", options={}`. This is mostly used if you want to instantiate and use your reporter with a structure of options.

Now you can init TestBox with your reporter:

```javascript
r = new TestBox( reporter="my.path.toCustomReporter" );
r = new TestBox( reporter= new my.path.CustomReporter() );
r = new TestBox( reporter={
    type = "my.path.to.CustomReporter",
    options = { name = value, name2 = value2 }
} );
```

## Sample Reporter

Here is a sample reporter for you that generates JSON for the output.

```javascript
component{

  function init(){ return this; }

  /**
  * Get the name of the reporter
  */
  function getName(){
    return "JSON";
  }

  /**
  * Do the reporting thing here using the incoming test results
  * The report should return back in whatever format they desire and should set any
  * Specifc browser types if needed.
  * @results.hint The instance of the TestBox TestResult object to build a report on
  * @testbox.hint The TestBox core object
  * @options.hint A structure of options this reporter needs to build the report with
  */
  any function runReport(
    required testbox.system.TestResult results,
    required testbox.system.TestBox testbox,
    struct options={}
  ){
    getPageContext().getResponse().setContentType( "application/json" );
    return serializeJSON( arguments.results.getMemento() );
  }

}
```


# Modules

Extend TestBox your way!

TestBox supports the concepts of modules just like how ColdBox has modules. They are self-contained packages that can extend the functionality of TestBox. They can listen to test creations, errors, failures, skippings and much more. To get started you can use the TestBox CLI to generate a module for you:

```bash
testbox generate module MyModule
```

### Module Layout

A TestBox module layout is similar to a ColdBox Module layout. They have to be installed at `/testbox/system/modules` to be discovered and loaded and have one mandatory file: `ModuleConfig.cfc` which must exist in the root of the module folder.

```
+ testbox/system/modules
  + myModule
    + ModuleConfig.cfc
```

You can install TestBox modules from ForgeBox via the `install` command:

```bash
install id=module directory=testbox/system/modules
```

#### Differences With ColdBox Modules

* There is no WireBox
* There is no Routing
* There is no Scheduling
* There is no Interceptors
* There is no Views
* Inception works, but limited
* No module dependencies, all modules are loaded in discovered order

### ModuleConfig

This is the main descriptor file for your TestBox module.

#### Mandatory Callbacks

It must have three mandatory callbacks:

* `configure()` - Configures the module for operation
* `onLoad()` - When the module is now activated
* `onUnload()` - When the module is deactivated

```cfscript
component{

  function configure(){
  }
  
  function onLoad(){
  }
  
  function onUnload(){
  }
}
```

#### Injected Properties

The following are the injected properties:

| **Property**       | **Description**                   |
| ------------------ | --------------------------------- |
| **ModulePath**     | The module’s absolute path        |
| **ModuleMapping**  | The module’s invocation path      |
| **TestBox**        | The testbox reference             |
| **TestBoxVersion** | The version of TestBox being used |

#### Injected Methods

The following are injected methods:

| **Method**              | **Description**             |
| ----------------------- | --------------------------- |
| **getEnv()**            | Get an environment variable |
| **getSystemSetting()**  | Get a Java system setting   |
| **getSystemProperty()** | Get a Java system property  |
| **getJavaSystem()**     | Get the Java system class   |

### Module Loading Failures

If a module fails to be activated, it will still be in the module registry but marked inactive via the `active` boolean key in its registry entry. You will also find the cause of the failure in the console logs and the key `activationFailure` of the module's registry entry.

```cfscript
writedump( testbox.getModuleRegistry() )
```

{% hint style="info" %}
Not all ColdBox/CommandBox modules can be TestBox modules. Remember that TestBox modules are extremely lightweight and testing focused.
{% endhint %}

### Testing Callbacks

This ModuleConfig can also listen to the following test life-cycle events. It will also receive several arguments to the call. Here are the common descriptions of the arguments

* `target` - The bundle in question
* `testResults` - The TestBox results object
* `suite` - The suite descriptor
* `suiteStats` - The stats for the running suite
* `exception` - A ColdFusion exception
* `spec` - The spec descriptor
* `specStats` - The stats of the running spec

| **Callback**     | **Arguments**                                                                                                   |
| ---------------- | --------------------------------------------------------------------------------------------------------------- |
| onBundleStart()  | <ul><li>target</li><li>testResults</li></ul>                                                                    |
| onBundleEnd()    | <ul><li>target</li><li>testResults</li></ul>                                                                    |
| onSuiteStart()   | <ul><li>target</li><li>testResults</li><li>suite</li></ul>                                                      |
| onSuiteEnd()     | <ul><li>target</li><li>testResults</li><li>suite</li></ul>                                                      |
| onSuiteError()   | <ul><li>exception</li><li>target</li><li>testResults</li><li>suite</li></ul>                                    |
| onSuiteSkipped() | <ul><li>target</li><li>testResults</li><li>suite</li></ul>                                                      |
| onSpecStart()    | <ul><li>target</li><li>testResults</li><li>suite</li><li>spec</li></ul>                                         |
| onSpecEnd()      | <ul><li>target</li><li>testResults</li><li>suite</li><li>spec</li></ul>                                         |
| onSpecFailure()  | <ul><li>exception</li><li>spec</li><li>specStats</li><li>suite</li><li>suiteStats</li><li>testResults</li></ul> |
| onSpecSkipped()  | <ul><li>spec</li><li>specStats</li><li>suite</li><li>testResults</li></ul>                                      |
| onSpecError()    | <ul><li>exception</li><li>spec</li><li>specStats</li><li>suite</li><li>suiteSpecs</li><li>testResults</li></ul> |

### Manual Registration

You can also manually register and activate modules by using the `registerAndActivate( invocationPath )` method of the TestBox object. All you have to do is pass the invocation path to your modules' root folder:

```
testbox.registerAndActivate( "tests.resources.modules.MyModule" )
```

That's it! It will register it and activate and be ready to listen.


# Dry Run & Spec Discovery

Discover your test specs and suites without executing any test code — explore what would run before it runs.

TestBox 7 adds a **Dry Run** mode that traverses all your test bundles, discovers every `describe()` suite and `it()` spec (or xUnit test method), and reports what *would* run — without executing a single line of test code. Use it to:

* Verify your test structure before a long CI run
* Get an exact count of specs by label, tag, or directory
* Preview filter results (`--labels`, `--bundles`, etc.) without the overhead of actually running tests
* Quickly audit suite naming and nesting

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-88da83c3344691bf9344a6868f0b908947734970%2Ftestbox-boxlang-dryrun.gif?alt=media" alt="BoxLang dry-run preview"><figcaption><p>Dry-run output showing discovered suites and specs without executing them</p></figcaption></figure>

***

## Web Runner — `url.dryRun`

The standard `runner.bxm` web runner also supports dry run via a URL parameter:

```
http://localhost/tests/runner.bxm?dryRun=true
http://localhost/tests/runner.bxm?dryRun=true&directory=tests.specs.unit
http://localhost/tests/runner.bxm?dryRun=true&labels=integration
```

When `dryRun=true` the runner bypasses the `StreamingRunner` path and passes the flag through to the HTML runner, returning the spec discovery tree in the browser instead of executing tests.

{% hint style="info" %}
All the same filter parameters (`directory`, `bundles`, `labels`, `excludes`, `testSuites`, `testSpecs`) work alongside `dryRun=true` in the web runner, just as they do in the CLI.
{% endhint %}

***

## BoxLang CLI — `--dry-run`

Add the `--dry-run` flag to any `./testbox/run` invocation:

```bash
# Console output (default)
./testbox/run --dry-run

# Combine with directory/label filters
./testbox/run --directory=tests.specs.unit --dry-run
./testbox/run --labels=integration --dry-run

# Output raw JSON instead
./testbox/run --dry-run=json
```

The console output groups specs under their parent suites, colour-codes them by type, and prints a summary count at the end.

### JSON Dry-Run Output

Pass `--dry-run=json` to receive a machine-readable structure:

```bash
./testbox/run --dry-run=json
./testbox/run --bundles=tests.specs.MySpec --dry-run=json | jq '.totalSpecs'
```

The JSON document shape:

```json
{
  "totalBundles": 3,
  "totalSuites": 12,
  "totalSpecs": 47,
  "bundles": [
    {
      "bundle": "tests.specs.MySpec",
      "suites": [
        {
          "name": "My Feature",
          "specs": ["it should do X", "it should do Y"],
          "suites": []
        }
      ]
    }
  ]
}
```

***

## Programmatic Dry Run — `tb.dryRun()`

You can also trigger a dry run from CFML or BoxLang code via the `TestBox` instance:

### BoxLang

```javascript
var tb = new testbox.system.TestBox( bundles = "tests.specs" )
var results = tb.dryRun()

writeDump( var = results, label = "Dry-Run Results" )
```

### CFML

```javascript
var tb = new testbox.system.TestBox( bundles = "tests.specs" );
var results = tb.dryRun();

writeDump( var = results, label = "Dry-Run Results" );
```

### Programmatic JSON Output

```javascript
var tb      = new testbox.system.TestBox( bundles = "tests.specs" )
var results = tb.dryRun()

writeOutput( serializeJSON( results ) )
```

***

## Filtering Respected

Dry run honours **all the same filters** as a normal test run:

| Option       | Dry-Run Behaviour                                    |
| ------------ | ---------------------------------------------------- |
| `bundles`    | Limits discovery to specified bundles                |
| `directory`  | Limits discovery to bundles in the given directory   |
| `labels`     | Only specs/suites matching the label(s) are included |
| `excludes`   | Labels to exclude from discovery                     |
| `testSuites` | Limits to matching suite names                       |
| `testSpecs`  | Limits to matching spec names                        |

This means you can validate any filter combination before committing a `testbox run`.

***

## Use Cases

### Pre-flight Check

```bash
# How many specs exist in the integration suite?
./testbox/run --labels=integration --dry-run
```

### CI Matrix Planning

```bash
# Output JSON and parse it with jq
./testbox/run --dry-run=json | jq '.totalSpecs'
```

### Structure Audit

```bash
# Check all bundles at once
./testbox/run --directory=tests --dry-run
```

{% hint style="success" %}
Dry run is a zero-risk way to validate that your TestBox configuration, filter arguments, and bundle structure are correct before a real test run with side effects.
{% endhint %}


# Code Coverage

When writing tests for an app or library, it's generally regarded that more tests is better since you're covering more functionality and more likely to catch regressions as they happen. This is true, but more specifically, it's important that your tests run *as much code* in your project as possible. Tests obviously can't check code that they doesn't run!

With BDD, there is not a one-to-one correlation between a test and a unit of code. You may have a test for your login page, but how do you know if all the `else` blocks in your if statements or `case` blocks in your switch statements were run? Was your error routine tested? What about optional features, or code that only kicks in on the 3rd Tuesday of months in the springtime? These can be difficult questions to answer just by staring at the results of your tests. The answer to this is Code Coverage.

## Code Coverage

Code coverage does not replace your tests nor does it change how you write your tests. It's additional metrics gathered by the testing framework *while your tests are running* that actually tracks what lines of code were executed and what lines of code didn't get run. Now you can finally see how much code in your app is "covered" by your tests and what code is currently being untested.

TestBox supports code coverage statistics out-of-the box with no changes to your test suite and you can capture the data in a handful of ways, including a Coverage Browser report which visualizes every CF file in your code and shows you what lines executed and what lines didn't.

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/V2Nn8sEG3jBQfBuyUwKV/testbox-codecoverage-overview.png)

## Requirements

* TestBox 3.x+
* [FusionReactor ](https://www.fusion-reactor.com/)7+ (separate license required)

Please note that **FusionReactor** is a separate product not made by Ortus, but by **Intergral GmbH**. FusionReactor is a performance monitoring tool for Java-based servers and you will need to purchase a license to use it. We understand you may wish to use code coverage for free, but this feature would not have been possible without the line performance tracking feature of FusionReactor that allows us to match your Java bytecode to the actual code lines of your CFML. For personal use, there is a reasonably-priced [Developer Edition](https://www.fusion-reactor.com/fusionreactor-developer-version/). Please reach out to [FusionReactor's sales team](https://www.fusion-reactor.com/contact-us/) if you have any questions.


# Running Code Coverage

In order to use TestBox Code Coverage, you will need TestBox 3.x or higher installed, a licensed installation of [FusionReactor](https://www.fusion-reactor.com/) and a working test suite. You may have some or all of these already so skip the sections that don't apply to you.

## Fusion Reactor

If you don't have FusionReactor installed, you can do so very easily in CommandBox like so:

```bash
install commandbox-fusionreactor
fr register <Your license key here>
```

That's it! All servers you start now will have FusionReactor configured. You can open FusionReactor's web console via the menu item in your server's tray icon. Note, the FusionReactor web admin is not required to get TestBox code coverage.

If you are not using CommandBox for your server, follow the [installation instructions](https://www.fusion-reactor.com/manually-installing-fusionreactor/) on FusionReactor's website. If you need a license key, please [contact FusionReactor](https://www.fusion-reactor.com/download/) to acquire one. Note they have a 2 week trial you can use.

## TestBox 3.x+

To get the latest version of TestBox into a new project, you can install it via CommandBox like so:

```bash
install testbox --saveDev
```

The `--saveDev` flag will store TestBox as a development dependency.

To update a previous installation of TestBox 2.x to the latest, you will need to explicitly ask for 3.x. Please note 3.x may have some breaking changes from 2.x and support different CF engines, so please review the [release notes](broken://pages/-LY2GS5RSsDY_0JE63YX) first.

```bash
install testbox@3
```

## Test Suite

If you don't have test suite yet, let's install a ColdBox sample app to play with. TestBox does not require ColdBox to work, but the mechanics of the test runner itself are identical so this is the easiest way to get one running. Run these CommandBox commands in an empty directory.

```bash
coldbox create app
server start
```

Inside your directory will be a folder called `/tests` which has our test runner `/tests/runner.cfm`. Code coverage is opt-in, so you will need to open your `runner.cfm` and default code coverage enabled to true.

```
<!--- Code Coverage requires FusionReactor --->
<cfparam name="url.coverageEnabled"    default="true">
```

## Run your Test Suite

All you need to do now is run your test suite. You can do so by hitting `/tests/runner.cfm` in the URL of your browser, or use the `testbox run` command in CommandBox.

You don't need to configure anything for code coverage to work. TestBox will auto-detect if FusionReactor is installed on your server and will generate the code coverage results for you. In the output of your test reporter, you will see a percentage to represents the number of lines of code (LOC) which were executed divided by the total number of lines of code. Note, code coverage only counts executable lines of code against you, so comments, whitespace, or HTML do not count as an executable LOC.

Keep reading in the next section to find out how to configure the details of code coverage to only look at the files you want and also how to generate the Code Coverage Browser.

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/V2Nn8sEG3jBQfBuyUwKV/testbox-codecoverage-overview.png)


# Configuring Code Coverage

By default, code coverage will track all .cfc and .cfm files in your web root. However, for the most correct numbers, you want to only track the code in your app. This means you'll want to ignore things like

* 3rd party frameworks such as ColdBox or TestBox itself
* 3rd party modules installed by CommandBox (i.e., your `/modules` folder)
* Backups or build directories that aren't actually part of your app
* Parts of the app that you aren't testing such as the `/tests` folder itself

Most of the coverage settings are devoted to helping TestBox know what files to track, but there are some other ones too. Let's review them.

## Default Settings

Code coverage is **disabled by default** and set with a default configuration. You can control how it behaves with a series of `<CFParam>` tags in your `/tests/runner.cfm` file. If you created a fresh new ColdBox app from our app templates using `coldbox create app`, you'll see there are already configuration options ready for you to change. If you are working with an existing test suite runner, place the following lines PRIOR to the `<CFInclude>` in your runner.cfm.

```markup
<!--- Code Coverage requires FusionReactor --->
<cfparam name="url.coverageEnabled"                    default="false">
<cfparam name="url.coveragePathToCapture"            default="#expandPath( '/' )#">
<cfparam name="url.coverageWhitelist"                default="">
<cfparam name="url.coverageBlacklist"                default="/testbox,/coldbox,/tests,/modules,Application.cfc,/index.cfm">
<!---<cfparam name="url.coverageBrowserOutputDir"        default="#expandPath( '/tests/results/coverageReport' )#">--->
<!---<cfparam name="url.coverageSonarQubeXMLOutputPath"    default="#expandPath( '/tests/results/SonarQubeCoverage.xml' )#">--->
```

## Configuration Options

Let's go over the options above and what they do. Feel free to comment/uncomment and modify them as you need for your code. Note, any of these settings can be overridden by a URL variable as well.

## coverageEnabled

Set this to `true` or `false` to enable the code coverage feature of TestBox. Setting this to `true` without FusionReactor installed will be ignored.

The following setting would turn on code coverage:

```markup
<cfparam name="url.coverageEnabled" default="true">
```

{% hint style="warning" %}
**Changed in TestBox 7.1:** this setting now defaults to `false`. Previously it defaulted to `true`, so every runner hit attempted to start coverage even on installs with no FusionReactor. Coverage is now opt-in: set the param to `true`, or pass `?coverageEnabled=true` on the URL.
{% endhint %}

## coveragePathToCapture

Use this to point to the root folder that contains code you wish to gather coverage data from. This must be an absolute path and feel free to use any CF Mappings defined in your `/tests/Application.cfc` to make the path dynamic. This is especially useful if the app being tested is in a subfolder of the actual web root. There is nominal overhead in gathering the coverage data from files, so set this to the correct folder and instead of using the whitelist to filter down from your web root if possible.

This setting defaults to the web root. Also note, code coverage only looks at files ending in `.cfc` or .`cfm` so there's no need to filter additionally on that unless you want to only include, say, `.cfc` files.

```markup
<cfparam name="url.coveragePathToCapture" default="C:/absolute/path/to/webroot/">
```

## coverageWhitelist

This is a comma-delimited list of file globbing patterns relative to the `coveragePathToCapture` setting that further filters what files and folders to track. By default this setting is empty, which means ALL CFML code in the coverage path will be tracked. As soon as you specify at least one file globbing path in the whitelist, ONLY the files matching the whitelist will be tracked.

For example, if you only cared about handlers and models in an MVC app, you could configure a whitelist of:

```markup
<cfparam name="url.coverageWhitelist" default="/handlers/,/models/">
```

Note, all the basic rules of file globbing apply here. To give you a quick review

* Use `?` to match a single char like `/Application.cf?`
* Use `*` to match multiple characters within a folder or file like `/models/*Service.cfc`.
* Use `**` to match multiple characters in any sub folder (recursively) like `/models/**.cfc`.
* A pattern like `foo` will match any file or folder recursively but a leading slash like `/foo` locks that pattern to the root directory so it's not a recursive match.
* A trailing slash forces a directory match like `/tests/`, but no trailing slash like `/tests` would also match a file such as `/tests-readme.md`.

## coverageBlacklist

This is a comma-delimited list of file globbing patterns relative to the `coveragePathToCapture` setting that is applied *on top of* any whitelist patterns to prune back folders or files you don't want to track. There's no reason to include a path in the blacklist if you have a whitelist specified and that whitelist already doesn't include the path in question. However, a blacklist can be very handy when you want to include everything but a few small exceptions and it's easier to list those exceptions rather than create a large number of paths in the whitelist.

```markup
<cfparam name="url.coverageBlacklist" default="/testbox/,/build/,/myTest.cfm">
```

## coverageBrowserOutputDir

One of the most visually exciting features of Code Coverage is the ability to generate a stand-alone HTML report that allows you inspect every tracked file in your project and see exactly what lines of code are "covered" by your tests and what is not. The Code Coverage Browser is a mini-site of static HTML files in a directory which you can open in a browser on any computer without the need for a CF engine or TextBox being present. (read, you can zip them up and send them to your boss or store as a build artifact!)

To enable the Code Coverage Browser, uncomment the param for it and specify an absolute file path to where you would like the static mini-site created. You will want a dedicated directory such as `/tests/results/coverageReport` but just remember to expand it so it's absolute. The directory will be created if it doesn't exist.

```markup
<cfparam name="url.coverageBrowserOutputDir" default="#expandPath( '/tests/results/coverageReport' )#">
```

Also note, Windows is pesky about placing file and folder locks on your report output directory if you have it open in Windows Explorer. If you get an error about not being able to delete the report directory, close all Explorer windows and try again. Sadly, there's no workaround for this as Windows is the one placing the locks!

## coverageSonarQubeXMLOutputPath

SonarQube is a code quality tool that gathers information about your code base for further reporting. If you don't use SonarQube, you may ignore this section. You can have TestBox spit out a coverage XML file in the format that SonarQube requires by uncommenting this param and specifying an absolute file path to where you'd like the file written. Please include the file name in the path.

```markup
<cfparam name="url.coverageSonarQubeXMLOutputPath" default="#expandPath( '/tests/results/SonarQubeCoverage.xml' )#">
```


# Known Behaviors

There are a few known issues with code coverage that are currently out of our control. We apoligize for any inconvenience they may give you.

## Occasional blank page on Lucee when running tests after restart

On some sites we've experienced that after a fresh restart of Lucee Server, when the first page you hit is the test suite and code coverage is enabled, Lucee throws a low level compilation error (which you can see in the logs) and a white page is returned to the browser. We haven't figured out the scenario in which occurs, but refreshing the page always seems to work the second time.

If you run into this on an automated build environment, consider configuring your build to hit a page first, or run the tests again if no results are captured the first run.

## Very large CF files won't capture code coverage

This has been reported in Lucee for very large files of CF code. Lucee automatically breaks bytecode into additional methods when compiling to avoid the JVM limits of maximum method sizes in a class file. However, when FusionReactor instruments the byte code (adds additional lines of code in), it can push some of the internal methods over the JVM limit. There will be an error logged to your console and TestBox will have no coverage for the file, showing every line as not executed.

The only workaround at this time is to reduce the size of your CF files so the bytecode isn't as close to the JVM limits. Try moving chunks of code out to includes.

## Adobe incorrectly calculates coverage for files which did not run at all

Only executable code should be tracked, meaning a comment, whitespace, or HTML that does not run will not count against your total coverage percentage. When using Adobe ColdFusion, if there are any CF files which did not run at all (and therefore were not compiled) they will count every line in the file as executable since FusionReactor is only capable of tracking files which are compiled. Lucee has a workaround to manually force compilation on such files, but Adobe does not.

The best work around is to improve your tests so that these files are being executed! Alternatively, you can add those files to the blacklist until you are ready to write tests for them, but that will make your coverage look better than it really is if you do eventually want to write tests for those files. Minimally, a test that does nothing but create an instance of a CFC would be enough to trigger its compilation so correct coverage can kick in.

## Why didn't this ending curly brace, etc get tracked correctly?

Occasionally you may run across some lines of code in the Code Coverage Browser report that doesn't seem correctly tracked. Common offenders are extra curly braces or ending tags floating on a line of their own. The fact is, mapping each line of CF code to the actual lines of compiled bytecode is tricky business and done entirely by the CF engines (Adobe, Lucee) under the hood during compilation. Sometimes bits of code might not seem tracked correctly, but we've never seen it have any significant effect on your overall coverage data. The behavior is specific to each engine/version but typically lines like that just get associated with the next executable line, so once your coverage for a file hits all the possible lines, the issue goes away :) Feel free to report any issues you see. We have some workarounds in place and can see about making it better.

## My coverage statistics all of a sudden show 0% or weird numbers for code I know that is runnning

TestBox's code coverage feature relies on byte code instrumentation from Fusion Reactor. It seems that in some instances this process can fall over due to FR's internal behaviour, byte code class caching, internal compilation changes going from one version of your CFML engine to another one and other reasons. While we report these kind of issues upstream, unfortunately they are nearly impossible for us to properly investigate and debug.

One common symptom seems to be that code coverage statistics for individual files or your overall codebase vary extremely between two TestBox executions without having changed code at all or in a meaningful way. Another symptom observed by users is that code coverage drops to 0% for certain files and you know for sure that these files would be executed during your tests.

A restart of your CFML engine and a subsequent run of your tests with code coverage usually fixes this problem.


# Continous Integration

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/WR4AQ3VJTSAvzI8ySazd/The-Existing-Challenges-of-Continuous-Integration-CI.png)

[Continuous Integration](https://en.wikipedia.org/wiki/Continuous_integration) (CI) is a development process that requires developers to **integrate** their code into a shared source code repository (git,svn,mercurial,etc) several times a day, while a monitoring process detects code commits and acts upon those commits. Those actions can be the actual checkout of branches, execution of build processes, quality control, and of course our favorite; automated testing.

TestBox can integrate with all major CI servers as all you need to do is be able to execute your test suites and produce reports. You can see that in our [Running Tests](/getting-started/running-tests) section and [Reporters](/digging-deeper/reporters).

## Benefits of Continuous Integration

* Decrease the feedback loop
* Discover defects faster before production releases
* Developer Accountability
* Increase code visibility and promote communication
* Increase quality control
* Reduce integration issues with other features
* Develop in an Agile/Scrum fashion with continuous improvement
* Much More...

## CI Servers

Here is a listing of some of the major CI servers:

* Jenkins - <https://jenkins.io/>
* Gitlab - <https://gitlab.com/>
* Travis - <https://travis-ci.org/>
* Bamboo - <https://www.atlassian.com/software/bamboo>
* TeamCity - <https://www.jetbrains.com/teamcity/>


# Github Actions

![GitHub Actions logo](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/Jx5NsFYwYXoZ7YzpDrjV/github-actions-logo.png)

## About GitHub Actions

[GitHub Actions](https://github.com/features/actions) is an automation platform built in to GitHub.com that makes it easy to automate code quality on your github repos. There are a number of integrations that make using TestBox inside GitHub Actions simple, speedy and powerful so you can get back to writing code.

## Features

* FREE for public repositories
* 2,000 minutes for private repos
* Can reuse workflows, i.e. for a standard `test.yml` workflow in both builds and PR testing
* Can schedule workflow runs
* \[Can configure a build "matrix"], i.e. for [testing against all recent CFML engines](https://github.com/coldbox-modules/cborm/blob/development/.github/workflows/tests.yml#L20-L25)
* [Thousands of configurable, reusable "Actions"](https://github.com/marketplace?category=\&query=\&type=actions\&verification=)
* [Can notify Slack on build failure](https://github.com/marketplace/actions/slack-notify)

### TestBox Integration

Testing your application with TestBox in GitHub Actions (GHA) begins a `workflow.yml` file at the root of a `.github/workflows/` directory. You can name this file anything you like - I'd suggest `build.yml` or `test.yml` - but if it is not a valid Yaml file the GHA workflow will fail.

This file should start with some GHA metadata to dictate when and how the workflow should run:

```yml
# .github/workflows/tests.yml
name: Test

on:
  push:
    branches:
      - main
      - master
      - development
```

This will run the workflow on each commit to the `master` or `main` branch. Next, specify a workflow job to execute:

```yml
jobs:
  tests:
    name: Tests
    runs-on: ubuntu-latest
    steps:
      - # All job steps go here
```

Under the `jobs.tests.steps` is where we will place each sequential testing step. First, we need to check out the repository code and install Java and CommandBox:

```yml
      - name: Checkout Repository
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Setup Java
        uses: actions/setup-java@v2
        with:
          distribution: "adopt"
          java-version: "11"

      - name: Setup BoxLang
        uses: Ortus-Solutions/setup-boxlang@main
        with:
          modules: bx-cli
          commandbox-modules: testbox-cli
```

If we need to install dependencies, we would do that now:

```yml
      - name: Install dependencies
        run: box install
```

And finally, we can start a CFML server of our choice using CommandBox, before using the `testbox run` command to run our test suite:

```yml
      - name: Start server
        run: box server start cfengine=lucee@5.3 --noSaveSettings

      - name: Run TestBox Tests
        run: box testbox run
```

> If you are using a testing matrix to test against multiple CFML engines, replace `lucee@5.3` with `${{ matrix.cfengine }}`. [See an example here](https://github.com/coldbox-modules/hyper/blob/main/.github/workflows/release.yml#L37)

The full example would look something like this:

```yml
# .github/workflows/tests.yml
name: Test

on:
  push:
    branches:
      - main
      - master
      - development
jobs:
  tests:
    name: Tests
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Setup Java
        uses: actions/setup-java@v2
        with:
          distribution: "adopt"
          java-version: "11"

      - name: Setup BoxLang
        uses: Ortus-Solutions/setup-boxlang@main
        with:
          modules: bx-cli
          commandbox-modules: testbox-cli

      - name: Install dependencies
        run: box install

      - name: Start server
        run: box server start cfengine=lucee@5.3 --noSaveSettings

      - name: Run TestBox Tests
        run: box testbox run
```

{% hint style="info" %}
Running browser tests with bx-playwright? See the [browser tests GitHub Actions workflow](/browser-testing/running-browser-tests#github-actions), which installs the browser, caches it, starts your web server and uploads the screenshots and traces of failed specs.
{% endhint %}

### Box.json

In order for the `box testbox run` to execute correctly, our `box.json` in our project must be able to connect to our server and know which tests to execute. Here's a basic example showing the most important testbox property: the `testbox.runner` property:

```javascript
{
    "name" : "Package Name",
    // ForgeBox unique slug
    "slug" : "",
    // semantic version of your package
    "version" : "1.0.0+buildID",
    // author of this package
    "author" : "Luis Majano <lmajano@ortussolutions.com>",
    // location of where to download the package, overrides ForgeBox location
    "location" : "URL,Git/svn endpoint,etc",

    // testbox integration
    testbox :{
        // The location of the runner
        runner : [
            { "default": "http://localhost:8080/tests/runner.cfm" }
        ]
    }
}
```

We can also [skip setting the `testbox.runner` property and use the `box testbox run "http://localhost:8080/tests/runner.cfm"` command format instead.](https://commandbox.ortusbooks.com/testbox-integration/test-runner#run-unit-test-suite-from-the-command-line) Just be aware that the TestBox integration offers a ton of configuration in case you need to skip certain tests, etc. from your GitHub Actions test run.

> See [the CommandBox docs for box.json](https://commandbox.ortusbooks.com/package-management/box.json/testbox#testbox.runner) for more details.

## Online Example

[CBORM](https://github.com/coldbox-modules/cborm) is an ORM utility wrapper for ColdBox that takes the pain out of using ORM in CFML. CBORM uses GitHub Actions to test all new commits, to package up new module versions, and even to [format all CFML code for every new PR](https://github.com/coldbox-modules/cborm/blob/development/.github/workflows/pr.yml#L29).

See [All CBORM Workflows](https://github.com/coldbox-modules/cborm/tree/development/.github/workflows), or see [recent GitHub Actions workflow runs here](https://github.com/coldbox-modules/cborm/actions).


# Gitlab

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/vDZA8bw9tEKeAZnFbJF0/gitlab.png)

[Gitlab](https://www.gitlab.com) is one of the most popular collaboration software suites around. It is not only a CI server, but a source code server, docker registry, issue manager, and much much more. They are our personal favorite for private projects due to their power and flexibility.

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/ZfNo8VuYRN5A5RWqs9dp/gitlab-ci.png)

## Features

* All in one tool: CI, repository, docker registry, issues/milestones, etc.
* Same as Travis in concept - CI Runner
* Docker based
* CI Runners can be decoupled to a docker swarm
* Idea of CI pipelines
  * Pipelines composed of jobs executed in stages
  * Jobs can have dependencies, artifacts, services, etc
  * Schedule Pipelines (Cron)
  * Jobs can track environments
* Great stats + charting

## TestBox Integration

In order to work with Gitlab you must create a `.gitlab-ci.yml` file in the root of your project. Once there are commits in your repository, Gitlab will process this file as your build file. Please refer to the Gitlab Pipelines [documentation](https://docs.gitlab.com/ee/ci/pipelines.html) for further study.

We will leverage the [Ortus Solutions CommandBox Docker](https://hub.docker.com/r/ortussolutions/commandbox/) image in order to provide us with the capability to run any CFML engine and to execute tests. Please note that Gitlab runs in a docker environment.

```yaml
image: ortussolutions/commandbox:alpine

stages:
  - build
  - test
  - deploy

build_app:
  stage: build
  script:
    # Install dependencies
    - box install production=true

run_tests:
  stage: test
  only:
    - development
  # when: manual, always, on_success, on_failure
  script:
      - box install && box server start
      - box testbox run
```

The build file above leverages the `ortussolutions/commandbox:alpine` image, which is a compact and secure image for CommandBox. We then have a few stages (build,test,deploy), but let's focus on the `run_tests` job.

```yaml
run_tests:
  stage: test
  only:
    - development
  # when: manual, always, on_success, on_failure
  script:
      - box install && box server start
      - box testbox run
```

We define which branches it should listen to: `development`, and then we have a `script` block that defines what to do for this job. Please note that the `when` action is commented, because we want to execute this job every time there is a commit. In Gitlab we can determine if a job is manual, scheduled, automatic or dependent on other jobs, which is one of the most flexible execution runners around.

In our script we basically install our dependencies for our project using CommandBox and startup a CFML server. We then go ahead and execute our tests via `box testbox run`.

### Box.json

In order for the `box testbox run` to execute correctly, our `box.json` in our project must be able to connect to our server and know which tests to execute. Below are all the possiblities for the `testbox` integration object in CommandBox's `box.json`. (See [the CommandBox docs for box.json](https://commandbox.ortusbooks.com/package-management/box.json/testbox#testbox.runner) for more details.)

```javascript
{
    "name" : "Package Name",
    // ForgeBox unique slug
    "slug" : "",
    // semantic version of your package
    "version" : "1.0.0+buildID",
    // author of this package
    "author" : "Luis Majano <lmajano@ortussolutions.com>",
    // location of where to download the package, overrides ForgeBox location
    "location" : "URL,Git/svn endpoint,etc",

    // testbox integration
    testbox :{
        // The location of the runner
        runner : [
            { "default": "http://localhost:8080/tests/runner.cfm" }
        ],
        // Which labels to run, empty means all
        "labels" : "",
        // Which reporter to use, default is json
        "reporter" : "",
        // Which CFC bundles to execute, default is all
        "bundles" : "",
        // Which directories to execute
        "directory" : "tests.specs",
        // Recurse the directories for CFCs
        "recurse" : true,
        // Which bundles to filter on
        "testBundles" : "",
        // Which suites to filter on
        "testSuites" : "",
        // Which specs to filter on
        "testSpecs" : "",
        // Display extra details inlcuding passing and skipped tests.
        "verbose" : true,
        // How may milliseconds to wait before polling for changes, defaults to 500 ms
        "watchDelay" : 500,
        // Command delimited list of file globbing paths to watch relative to the working directory
        "watchPaths" : "**.cfc"
    }
}
```

## Online Example: cbVue

You can look at our `cbVue` sample application online: <https://gitlab.com/lmajano/cbvue> which contains all CI server integrations.


# Travis

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/9zg1cIqCW7MYGhj2jdK6/travis-ci.png)

[Travis CI](https://travis-ci.org) is one of the most popular CI servers for open source software. At Ortus Solutions, we use it for all of our open source software due to its strength of pull request runners and multi-matrix runners. They have both free and commercial versions, so you can leverage it for private projects as well.

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/EZV3ed2e5hw47HQHbIYv/travis-projectview.png)

## Features

* FREE for Open Source Projects
* Runs distributed VM’s and Container Support
* Triggers Build Script via git repository commits (`.travis.yml`)
* Multiple language support
* Many integrations and extensions
* Many notification types
* No ability to schedule/manual builds
* Great for open source projects!

## TestBox Integration

In order to work with Travis you must create a `.travis.yml` file in the root of your project. Once there are commits in your repository, Travis will process this file as your build file. Please refer to the [Travis Documentation](https://docs.travis-ci.com) for further study.

```yaml
language: java
sudo: required
dist: trusty

before_install:
  # CommandBox Keys
  - curl -fsSl https://downloads.ortussolutions.com/debs/gpg | sudo apt-key add -
  - sudo echo "deb https://downloads.ortussolutions.com/debs/noarch /" | sudo tee -a
  /etc/apt/sources.list.d/commandbox.list

install:
  - sudo apt-get update && sudo apt-get --assume-yes install commandbox
  - box install
  - box server start

script:
  - box testbox run
```

This build file is based on the `java` language and an Ubuntu Trusty image. We start off by executing the `before_install` step which installs all the OS dependencies we might need. In our case we add the CommandBox repository server keys and install CommandBox as our dependency. We then move to our `install` step which makes sure we have all the required software dependencies to execute our tests, again this looks at our `box.json` for TestBox and required project dependencies. After issuing the `box install` we move to starting up the CFML engine using `box server start` and we are ready to test.

```yaml
install:
  - sudo apt-get update && sudo apt-get --assume-yes install commandbox
  - box install
  - box server start
```

The testing occurs in the `script` block:

```yaml
script:
  - box testbox run
```

In our script we basically install our dependencies for our project using CommandBox and startup a CFML server. We then go ahead and execute our tests via `box testbox run`.

### Box.json

In order for the `box testbox run` to execute correctly, our `box.json` in our project must be able to connect to our server and know which tests to execute. Below are all the possiblities for the `testbox` integration object in CommandBox's `box.json`. (See [the CommandBox docs for box.json](https://commandbox.ortusbooks.com/package-management/box.json/testbox#testbox.runner) for more details.)

```javascript
{
    "name" : "Package Name",
    // ForgeBox unique slug
    "slug" : "",
    // semantic version of your package
    "version" : "1.0.0+buildID",
    // author of this package
    "author" : "Luis Majano <lmajano@ortussolutions.com>",
    // location of where to download the package, overrides ForgeBox location
    "location" : "URL,Git/svn endpoint,etc",

    // testbox integration
    testbox :{
        // The location of the runner
        runner : [
            { "default": "http://localhost:8080/tests/runner.cfm" }
        ],
        // Which labels to run, empty means all
        "labels" : "",
        // Which reporter to use, default is json
        "reporter" : "",
        // Which CFC bundles to execute, default is all
        "bundles" : "",
        // Which directories to execute
        "directory" : "tests.specs",
        // Recurse the directories for CFCs
        "recurse" : true,
        // Which bundles to filter on
        "testBundles" : "",
        // Which suites to filter on
        "testSuites" : "",
        // Which specs to filter on
        "testSpecs" : "",
        // Display extra details inlcuding passing and skipped tests.
        "verbose" : true,
        // How may milliseconds to wait before polling for changes, defaults to 500 ms
        "watchDelay" : 500,
        // Command delimited list of file globbing paths to watch relative to the working directory
        "watchPaths" : "**.cfc"
    }
}
```

## Online Example: cbVue

You can look at our `cbVue` sample application online: <https://travis-ci.org/coldbox-samples/cbvue> which contains all CI server integrations.


# Overview

Drive a real browser from your TestBox specs with bx-playwright.

TestBox can drive a real browser (Chromium, Firefox or WebKit) from your specs through the [bx-playwright](https://bxplaywright.boxlang.io) module. Your specs visit pages, click, fill forms and assert on what a user actually sees, with the same `describe()`, `it()` and `expect()` you already write.

{% file src="/files/LNjLkDmtdGb7POERERVb" %}
Browser testing in TestBox 7.2, in 80 seconds
{% endfile %}

{% hint style="info" %}
Browser specs and the [browser matchers](/browser-testing/browser-matchers) require BoxLang, because bx-playwright only runs on BoxLang. Write browser specs as BoxLang classes (`.bx`) and keep them in a folder that your CFML engine runs exclude: on Lucee or Adobe the browser annotations do nothing, so `browse()` is not defined and calling it errors. On BoxLang without bx-playwright, `browse()` and `this.playwright()` skip the running spec with an install hint, so the rest of your suite still runs:

* `bx-playwright is not installed: install-bx-module bx-playwright`

The features that browser tests rely on, [attachments](/browser-testing/attachments), [retries](/browser-testing/retries), `Playwright.AssertionFailed` counted as a failure and the [`--failed` runner option](/browser-testing/running-browser-tests#rerun-what-failed-failed), work for every spec on every engine.
{% endhint %}

## Why Browser Tests?

Unit and integration specs call your code directly. A browser test exercises the whole stack the way a user does: routing, templates, JavaScript, CSS and the network all take part. bx-playwright brings two things that make those tests reliable:

* **A real browser.** Pages render and run their JavaScript exactly as they do for your users, headless in CI or headed while you debug.
* **Web-first assertions.** Every assertion retries until it passes or its timeout expires (5 seconds by default), so you never sprinkle `sleep()` calls to wait for an element or a redirect.

TestBox adds the testing glue on top: one browser per bundle, fresh isolated pages per spec, `expect()` [matchers](/browser-testing/browser-matchers) for pages and locators, failure screenshots, traces and videos [attached to the spec](/browser-testing/attachments), [retries](/browser-testing/retries) for flaky specs, and runner options to [start your web server and rerun only what failed](/browser-testing/running-browser-tests).

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-7b315061d2136f658b73cc7296dcc75b4474046b%2Fbrowser-testing-demo.gif?alt=media" alt="A browser spec signing in to a demo shop and checking the dashboard"><figcaption><p>A browser spec signing in and checking the dashboard</p></figcaption></figure>

And when a spec fails, you get the evidence on the failing spec in your report:

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-2dbc1aba6fd7321e749fbc678f1c67ba07dec08f%2Fbrowser-testing-report-attachments.png?alt=media" alt="A failing browser spec in the HTML report with its screenshot, trace and video attached"><figcaption><p>Screenshot, trace and video attached to a failing spec</p></figcaption></figure>

## Installation

bx-playwright needs BoxLang 1.17+ and Java 21+. TestBox needs a bx-playwright version that provides `playwrightEnsureBrowser()`, the first stable bx-playwright release or later. Install the module into your BoxLang runtime:

```bash
install-bx-module bx-playwright
```

That is all you need locally: the first time a bundle opens a browser, TestBox installs the browser of its profile through `playwrightEnsureBrowser()`. The first run needs network access and is slower while the browser downloads. On Linux, the system libraries the browser needs are not part of that download: install them once with `bxplaywright install chromium --with-deps` (or your profile's browser).

For CI or offline machines, install the browser up front and turn the download off with `@browserAutoInstall( false )`, or call `ensureBrowserInstalled()` yourself, for example from `beforeAll()`:

```bash
bxplaywright install chromium --with-deps
bxplaywright doctor
```

More browsers, profiles and settings are covered in the [bx-playwright getting started guide](https://bxplaywright.boxlang.io/getting-started/).

## Your First Browser Spec

Add a browser annotation, such as `@browser`, `@browserProfile` or `@baseURL`, on the lines above `class`, and extend `testbox.system.BaseSpec` as usual. TestBox then [turns on browser support](#turning-on-browser-support) for the bundle. Inside a spec, call `browse()` with a closure: it receives a fresh page, and everything the page offers (`visit()`, `click()`, `fill()`, finders, locators and assertions) is the [bx-playwright browsing API](https://bxplaywright.boxlang.io/browsing/).

{% tabs %}
{% tab title="BDD - BoxLang" %}
{% code title="tests/specs/LoginSpec.bx" %}

```java
@baseURL( "http://localhost:8080" )
@browserProfile( "ci" )
class extends="testbox.system.BaseSpec" {

    function run() {
        describe( "Login", () => {

            it( "signs in with valid credentials", () => {
                browse( ( page ) => {
                    page.visit( "/login" )
                        .fill( "Email", "luis@ortus.com" )
                        .fill( "Password", "secret" )
                        .click( "Sign in" )

                    expect( page ).toHavePath( "/dashboard" )
                    expect( page ).toSee( "Welcome back" )
                } )
            } )

            it( "rejects a wrong password", () => {
                browse( ( page ) => {
                    page.visit( "/login" )
                        .fill( "Email", "luis@ortus.com" )
                        .fill( "Password", "nope" )
                        .click( "Sign in" )

                    expect( page ).toHavePath( "/login" )
                    expect( page.locator( "@error" ) ).toHaveText( "Invalid credentials" )
                } )
            } )

        } )
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="xUnit - BoxLang" %}
{% code title="tests/specs/LoginTest.bx" %}

```groovy
@baseURL( "http://localhost:8080" )
@browserProfile( "ci" )
class extends="testbox.system.BaseSpec" {

    function testSignsInWithValidCredentials() {
        browse( ( page ) => {
            page.visit( "/login" )
                .fill( "Email", "luis@ortus.com" )
                .fill( "Password", "secret" )
                .click( "Sign in" )

            expect( page ).toHavePath( "/dashboard" )
            expect( page ).toSee( "Welcome back" )
        } )
    }

    function testRejectsAWrongPassword() {
        browse( ( page ) => {
            page.visit( "/login" )
                .fill( "Email", "luis@ortus.com" )
                .fill( "Password", "nope" )
                .click( "Sign in" )
                // the bx-playwright inline assertions work too
                .assertPathIs( "/login" )
                .assertSee( "Invalid credentials" )
        } )
    }

}
```

{% endcode %}
{% endtab %}
{% endtabs %}

Run it like any other bundle, for example with the [BoxLang CLI runner](/getting-started/running-tests/boxlang-cli-runner):

```bash
./testbox/run --bundles=tests.specs.LoginSpec
```

You can assert in two styles, and mix them freely:

* TestBox [browser matchers](/browser-testing/browser-matchers): `expect( page ).toSee( "Welcome" )`, `expect( locator ).toBeVisible()`, with `not` forms.
* bx-playwright [assertions](https://bxplaywright.boxlang.io/assertions/): `page.assertSee( "Welcome" )`, `page.expect( "h1" ).toHaveText( "Hi" )`. Their `Playwright.AssertionFailed` exceptions count as spec **failures**, not errors.

## Turning On Browser Support

Browser support is turned on by class annotations, not by a base class. Any spec whose class, or a class it extends, has one of these annotations gets it:

| Annotation                            | Description                                                                    |
| ------------------------------------- | ------------------------------------------------------------------------------ |
| `@browser`                            | Turns browser support on with the bx-playwright default profile.               |
| `@browserProfile( "ci" )`             | Turns it on with the given bx-playwright profiles, a list such as `ci,mobile`. |
| `@baseURL( "http://localhost:8080" )` | Turns it on with the URL relative visits resolve against.                      |

`@browserAutoInstall( false )` requires a pre-installed browser instead of downloading one on first use. It does not turn browser support on by itself.

```java
@browser
class extends="testbox.system.BaseSpec" {

    function run() {
        it( "shows the home page", () => {
            browse( ( page ) => page.visit( "http://localhost:8080/" ).assertSee( "Welcome" ) )
        } )
    }

}
```

When a bundle has browser support, the TestBox runner creates a `testbox.system.browser.BrowserSupport` for it and mixes these methods into the spec's `this` and `variables` scopes, so you call them unqualified:

* `browse( callback, options )`: run a closure with fresh, isolated browser pages.
* `browserAvailable()`: can browser specs run here? See [Skipping When No Browser Is Available](#skipping-when-no-browser-is-available).
* `ensureBrowserInstalled()`: install the profile browser, for example from `beforeAll()` when auto-install is off.
* `getBrowserSupport()`: the bundle `BrowserSupport`.
* `closeBrowser()`: close the bundle browser.

It also adds `this.playwright()`, the bundle manager (described below), and registers the [browser matchers](/browser-testing/browser-matchers) for every spec of the bundle. A public method your spec declares itself, with one of these names, is kept, not overridden.

{% hint style="warning" %}
Only **public** methods are kept. A private method with one of these names is replaced by the browser method, so make an override public.
{% endhint %}

* **Inherited.** The annotations are read from the spec class and every class it extends. Put `@browser` on your project base spec and every spec that extends it can browse. A spec can opt out with `@browser( false )`, even when its base spec turns it on.
* **Any base class.** It works for BDD and xUnit bundles, whatever they extend: `testbox.system.BaseSpec`, a ColdBox `BaseTestCase` or your own base spec.
* **BoxLang only.** The runner attaches browser support on BoxLang, where bx-playwright runs. On Lucee and Adobe the annotations are ignored, so keep browser specs out of CFML runs.

```java
// tests/resources/BaseBrowserSpec.bx: every spec that extends it gets browser support.
// It is abstract, so TestBox does not run it as a bundle.
@browserProfile( "ci" )
abstract class extends="testbox.system.BaseSpec" {
}
```

### `BrowserSpec`

`testbox.system.BrowserSpec` is an optional base class: it is a `testbox.system.BaseSpec` that carries the `@browser` annotation and declares no methods of its own. The runner mixes in the browser methods and closes the browser after the bundle. Specs that extend it keep working unless they call `super.browse()` or `super.closeBrowser()`, or override `closeBrowser()` expecting it to run after the bundle.

```java
@baseURL( "http://localhost:8080" )
class extends="testbox.system.BrowserSpec" {
    // ...
}
```

## How Browser Support Works

* **One browser per bundle.** The bundle starts one bx-playwright manager, and its browser, the first time a spec uses it. The runner closes it after the bundle, even when your `afterAll()` throws, so your own `beforeAll()` and `afterAll()` need no `super` calls. If a request aborts before the bundle ends, the browser stays open until the next test run that opens a browser, which closes it first. bx-playwright also closes anything left open when the module unloads or the JVM stops.
* **Fresh pages per `browse()`.** Every `browse()` call gets new pages, each in its own browser context (its own cookies, storage and session), and closes them when the closure ends. Specs never leak state into each other.
* **Matchers registered for you.** The [browser matchers](/browser-testing/browser-matchers) are registered for every spec of the bundle.
* **Failure artifacts attached.** When the closure throws, the screenshots, trace and videos your artifact policy kept are [attached to the spec](/browser-testing/attachments#automatic-browser-artifacts) and the exception is rethrown unchanged.

## Bundle Annotations

| Annotation           | Description                                                                                                                                               |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `browser`            | Turns browser support on. Not needed when `baseURL` or `browserProfile` is set.                                                                           |
| `baseURL`            | The URL relative visits such as `page.visit( "/login" )` resolve against.                                                                                 |
| `browserProfile`     | The bx-playwright [profiles](https://bxplaywright.boxlang.io/profiles/) for the bundle browser, a list such as `ci,mobile`. Profiles merge left to right. |
| `browserAutoInstall` | Set to `false` to require a pre-installed browser instead of downloading one on first use.                                                                |
| `retries`            | Rerun failing specs of the bundle. See [Retries](/browser-testing/retries).                                                                               |

When `baseURL` is not set, the bundle uses, in order:

1. The `--web-server-url` of the BoxLang runner, when the runner [started your web server](/browser-testing/running-browser-tests#start-a-web-server-for-the-run) (kept in `server.testbox.webServerURL`).
2. The bx-playwright `baseURL` setting, or the `BX_PLAYWRIGHT_BASEURL` environment variable.

When `browserProfile` is not set, bx-playwright uses its `defaultProfile` setting, or the profile named in the `BX_PLAYWRIGHT_PROFILE` environment variable. That makes `BX_PLAYWRIGHT_PROFILE=ci` a handy switch for CI runs, while `browserProfile` pins a profile for one bundle.

```java
// A mobile, dark mode bundle against staging
@baseURL( "https://staging.example.com" )
@browserProfile( "mobile,dark" )
class extends="testbox.system.BaseSpec" {
    // ...
}
```

## `browse()`

```java
any function browse( required function callback, struct options = {} )
```

| Argument   | Description                                                                                                                                                                    |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `callback` | The closure to run. It receives one page per declared argument.                                                                                                                |
| `options`  | Context options for bx-playwright `newContext()`, for example `{ viewport : { width : 390, height : 844 } }`, `{ timeouts : { assertion : 10000 } }` or an `artifacts` policy. |

`browse()` returns whatever the callback returns, so you can pull a value out of the page and assert on it afterwards:

```java
var title = browse( ( page ) => page.visit( "/" ).title() )
expect( title ).toInclude( "Home" )
```

### One page per argument: multi-user flows

Declare one argument per user. Each argument gets its own page in its **own browser context**, so two users can be signed in at once without sharing cookies:

```java
it( "shows a new message to the other user", () => {
    browse( ( alice, bob ) => {
        alice.visit( "/login" ).fill( "Email", "alice@example.com" ).fill( "Password", "secret" ).click( "Sign in" )
        bob.visit( "/login" ).fill( "Email", "bob@example.com" ).fill( "Password", "secret" ).click( "Sign in" )

        alice.visit( "/chat" ).fill( "Message", "Hi Bob" ).click( "Send" )

        // Web-first: waits until the message shows up for Bob
        expect( bob.visit( "/chat" ) ).toSee( "Hi Bob" )
    } )
} )
```

A callback that declares no arguments receives a single page as its first positional argument.

### Context options

The `options` struct applies to every page of the call. For example, a phone sized viewport and a longer assertion timeout:

```java
browse(
    ( page ) => {
        page.visit( "/" )
        expect( page.locator( "@mobile-menu" ) ).toBeVisible()
    },
    { viewport : { width : 390, height : 844 }, timeouts : { assertion : 10000 } }
)
```

See the bx-playwright [configuration reference](https://bxplaywright.boxlang.io/configuration/) for every option.

## `this.playwright()`

`this.playwright()` returns the bundle's bx-playwright manager, created on first use with the `browserProfile` and `baseURL` annotations. Use it for anything beyond `browse()`, such as the API request client, saved sessions or a page you manage yourself. Everything it starts closes after the bundle.

```java
it( "lists the products from the API", () => {
    var response = this.playwright().request().get( "/api/products" )
    expect( response.status() ).toBe( 200 )
} )
```

{% hint style="warning" %}
Call it as `this.playwright()`. An unqualified `playwright()` resolves to the bx-playwright built-in function, even inside a browser spec, and returns a **new** manager that ignores the bundle annotations and that the bundle does not close for you.
{% endhint %}

## Skipping When No Browser Is Available

On BoxLang, `browse()` and `this.playwright()` already skip the running spec when bx-playwright is missing. To skip whole suites up front, without even entering them, use `browserAvailable()` in a `skip` constraint:

```java
function run() {
    describe( title = "Checkout", skip = !browserAvailable(), body = () => {
        it( "pays with a card", () => {
            browse( ( page ) => {
                // ...
            } )
        } )
    } )
}
```

## Using the Browser From Any Spec

Browser support delegates to `testbox.system.browser.BrowserSupport`, which any BoxLang code can use directly, without the annotations. Close it yourself when you are done:

```java
class extends="testbox.system.BaseSpec" {

    function beforeAll() {
        variables.browser = new testbox.system.browser.BrowserSupport( this )
        addMatchers( new testbox.system.browser.BrowserMatchers() )
    }

    function afterAll() {
        variables.browser.close()
    }

    function run() {
        describe( "Home page", () => {
            it( "greets visitors", () => {
                variables.browser.browse( ( page ) => {
                    page.visit( "http://localhost:8080/" )
                    expect( page ).toSee( "Welcome" )
                } )
            } )
        } )
    }

}
```

## Thread Safety

A bx-playwright manager is not thread safe, and a bundle shares one. Do not use `asyncAll` on suites, or bundles, that browse. Run browser bundles sequentially.

## Learn More

{% content-ref url="/pages/Hi7XZ1KYbHbyuawURD00" %}
[Browser Matchers](/browser-testing/browser-matchers)
{% endcontent-ref %}

{% content-ref url="/pages/UrJ22dwzQUp9LDxhTvBX" %}
[Attachments](/browser-testing/attachments)
{% endcontent-ref %}

{% content-ref url="/pages/hrl8rdfTwRlHqg7HVo50" %}
[Retries](/browser-testing/retries)
{% endcontent-ref %}

{% content-ref url="/pages/yeL2CyiNJmkqxeNcL0TX" %}
[Running Browser Tests](/browser-testing/running-browser-tests)
{% endcontent-ref %}

The browser API itself is documented in the bx-playwright guides: [Browsing](https://bxplaywright.boxlang.io/browsing/), [Assertions](https://bxplaywright.boxlang.io/assertions/), [Testing](https://bxplaywright.boxlang.io/testing/) (artifacts, debugging, page objects) and [Building on bx-playwright](https://bxplaywright.boxlang.io/integrations/).


# Browser Matchers

TestBox expectations for bx-playwright pages and locators that wait for the page.

The browser matchers let you assert on bx-playwright pages and locators with the TestBox `expect()` DSL you already use:

```java
expect( page ).toHaveTitle( "Dashboard" )
expect( page ).toHavePath( "/dashboard" )
expect( page ).toSee( "Welcome" )
expect( page ).notToSee( "Error" )
expect( page.locator( ".todo" ) ).toHaveCount( 3 )
expect( page.locator( "@error" ) ).notToBeVisible()
```

{% hint style="info" %}
These matchers require BoxLang: they live in `testbox.system.browser.BrowserMatchers`, a BoxLang class built on bx-playwright. On BoxLang without bx-playwright, [browser](/browser-testing/browser-testing#turning-on-browser-support) bundles skip their specs before any matcher runs. Keep browser specs out of Lucee and Adobe runs: there the browser annotations do nothing.
{% endhint %}

## Web-First: They Wait

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0fdb43198fd3a0acc391a07e80ca2e487e9195b0%2Ftestbox-browser-matchers.gif?alt=media" alt="Browser matchers in a spec, a browser waiting for the page, and a failing toHaveCount() message"><figcaption><p>Browser matchers wait for the page and explain their failures</p></figcaption></figure>

Every browser matcher delegates to bx-playwright's [web-first assertions](https://bxplaywright.boxlang.io/assertions/). It **retries until it passes or the assertion timeout expires** (5 seconds by default), so a matcher waits for a redirect to land, a spinner to go away or a list to fill in:

```java
browse( ( page ) => {
    page.visit( "/todos" ).fill( "New todo", "Write docs" ).press( "New todo", "Enter" )
    // No sleep: waits until the third item renders
    expect( page.locator( ".todos li" ) ).toHaveCount( 3 )
} )
```

The `not` forms wait too: `notToSee( "Loading" )` passes as soon as the text goes away, instead of failing because it was still there on the first check.

Change the timeout with the bx-playwright `timeouts.assertion` setting, or per `browse()` call:

```java
browse( ( page ) => {
    // ...
}, { timeouts : { assertion : 10000 } } )
```

## Matchers at a Glance

| Matcher                                | Target          | Passes when                                                                               |
| -------------------------------------- | --------------- | ----------------------------------------------------------------------------------------- |
| [`toHaveTitle( title )`](#tohavetitle) | page            | The page title is exactly `title`, or matches a regex                                     |
| [`toHaveURL( url )`](#tohaveurl)       | page            | The full page URL is exactly `url`, or matches a regex                                    |
| [`toHavePath( path )`](#tohavepath)    | page            | The URL path is exactly `path`, ignoring scheme, host, query string and hash              |
| [`toSee( text )`](#tosee)              | page or locator | `text`, or a regex, is visible in the page or inside the locator                          |
| [`toHaveText( text )`](#tohavetext)    | locator         | The text of the first match is exactly `text` (whitespace normalized), or matches a regex |
| [`toBeVisible()`](#tobevisible)        | locator         | The first match is visible                                                                |
| [`toBeHidden()`](#tobehidden)          | locator         | The first match is hidden or not in the page                                              |
| [`toHaveCount( count )`](#tohavecount) | locator         | The locator matches exactly `count` elements                                              |
| [`toHaveValue( value )`](#tohavevalue) | locator         | The input, textarea or select has `value`, or a value matching a regex                    |

Every matcher has a negated form with the `not` prefix: `notToHaveTitle()`, `notToHaveURL()`, `notToHavePath()`, `notToSee()`, `notToHaveText()`, `notToBeVisible()`, `notToBeHidden()`, `notToHaveCount()` and `notToHaveValue()`. See the [Not Operator](/digging-deeper/expectations/not-operator).

### Pages and Locators

* A **page** is what `browse()` hands your closure, or what `visit()` and `newPage()` return.
* A **locator** points at elements of a page: `page.locator( ".todo" )`, `page.locator( "@error" )` (a `data-testid`), `page.byRole( "button", { name : "Save" } )`, `page.byLabel( "Email" )` and the other bx-playwright [finders](https://bxplaywright.boxlang.io/browsing/).

Arguments can be passed by position or by name (`toHaveCount( count = 3 )`). Where the table says "or a regex", pass a pattern built with `page.regex()`:

```java
expect( page ).toHaveTitle( page.regex( "^Order ##\d+" ) )
expect( page ).toHaveURL( page.regex( "/orders/\d+$" ) )
```

## Page Matchers

### `toHaveTitle()`

```java
expect( page ).toHaveTitle( required title )
expect( page ).notToHaveTitle( required title )
```

The page title is exactly `title`, or matches a `page.regex()` pattern.

```java
browse( ( page ) => {
    page.visit( "/dashboard" )
    expect( page ).toHaveTitle( "Dashboard" )
    expect( page ).toHaveTitle( page.regex( "^Dash" ) )
    expect( page ).notToHaveTitle( "Login" )
} )
```

### `toHaveURL()`

```java
expect( page ).toHaveURL( required url )
expect( page ).notToHaveURL( required url )
```

The full page URL, scheme, host, path and query string included, is exactly `url`, or matches a `page.regex()` pattern. Use [`toHavePath()`](#tohavepath) when only the path matters.

```java
expect( page ).toHaveURL( "http://localhost:8080/search?q=boxlang" )
expect( page ).toHaveURL( page.regex( "q=boxlang" ) )
expect( page ).notToHaveURL( page.regex( "/login" ) )
```

### `toHavePath()`

```java
expect( page ).toHavePath( required path )
expect( page ).notToHavePath( required path )
```

The URL path is exactly `path` (case sensitive), ignoring the scheme, host, query string and hash, like bx-playwright's `assertPathIs()`. It is the natural check after a redirect, because it does not depend on the `baseURL`:

```java
page.visit( "/login" )
    .fill( "Email", "luis@ortus.com" )
    .fill( "Password", "secret" )
    .click( "Sign in" )
expect( page ).toHavePath( "/dashboard" )      // http://localhost:8080/dashboard?tab=1 passes
expect( page ).notToHavePath( "/login" )
```

{% hint style="info" %}
`toHavePath()` is also a [Data Navigator matcher](/digging-deeper/expectations/data-navigator). The browser version only takes over for bx-playwright pages: for any other value, such as a struct, it runs the Data Navigator `toHavePath()`, so both keep working in the same spec.
{% endhint %}

### `toSee()`

```java
expect( pageOrLocator ).toSee( required text )
expect( pageOrLocator ).notToSee( required text )
```

`text`, or a `page.regex()` pattern, is visible in the page, or inside the locator when you pass one. It uses bx-playwright's `assertSee()`, and the negated form uses `assertDontSee()`.

```java
expect( page ).toSee( "Welcome back, Luis" )
expect( page ).notToSee( "Something went wrong" )

// Scope the search to part of the page
expect( page.locator( "nav" ) ).toSee( "Sign out" )
expect( page.locator( "nav" ) ).notToSee( "Sign in" )
```

## Locator Matchers

### `toHaveText()`

```java
expect( locator ).toHaveText( required text )
expect( locator ).notToHaveText( required text )
```

The text of the first matching element is exactly `text`, with whitespace normalized, or matches a `page.regex()` pattern. Use [`toSee()`](#tosee) on the locator for a partial match.

```java
expect( page.locator( "h1" ) ).toHaveText( "Your Orders" )
expect( page.locator( "@total" ) ).toHaveText( page.regex( "^\$\d+\.\d{2}$" ) )
expect( page.locator( "@status" ) ).notToHaveText( "Pending" )
```

### `toBeVisible()`

```java
expect( locator ).toBeVisible()
expect( locator ).notToBeVisible()
```

The first matching element is visible.

```java
page.click( "Menu" )
expect( page.locator( "@menu" ) ).toBeVisible()
expect( page.locator( "@error" ) ).notToBeVisible()
```

### `toBeHidden()`

```java
expect( locator ).toBeHidden()
expect( locator ).notToBeHidden()
```

The first matching element is hidden, or not in the page at all. Handy to wait for spinners and dialogs to go away:

```java
page.click( "Save" )
expect( page.locator( ".spinner" ) ).toBeHidden()
expect( page.locator( "@toast" ) ).notToBeHidden()
```

### `toHaveCount()`

```java
expect( locator ).toHaveCount( required count )
expect( locator ).notToHaveCount( required count )
```

The locator matches exactly `count` elements.

```java
expect( page.locator( ".cart li" ) ).toHaveCount( 2 )
expect( page.locator( ".cart li" ) ).notToHaveCount( 0 )
```

### `toHaveValue()`

```java
expect( locator ).toHaveValue( required value )
expect( locator ).notToHaveValue( required value )
```

The input, textarea or select has `value`, or a value matching a `page.regex()` pattern.

```java
page.fill( "Email", "luis@ortus.com" )
expect( page.byLabel( "Email" ) ).toHaveValue( "luis@ortus.com" )
expect( page.locator( "##country" ) ).toHaveValue( "US" )
expect( page.locator( "input[name=zip]" ) ).notToHaveValue( "" )
```

{% hint style="success" %}
Remember to escape `#` as `##` inside BoxLang strings, as in `page.locator( "##country" )`.
{% endhint %}

## Failure Messages

A matcher that does not pass in time fails the spec with a regular `TestBox.AssertionFailed` failure that carries bx-playwright's message: what was expected, what was received, and Playwright's call log of what it waited for. For example, `expect( page.locator( "li" ) ).toHaveCount( 5 )` on a list with one item fails with a message like:

```
Locator expected to have count: 5
Received: 1
Call log:
  - Expect "toHaveCount" with timeout 5000ms
  - waiting for locator("li")
  ...
```

The exact wording comes from Playwright. `withContext()` [prefixes](/digging-deeper/expectations#adding-context-to-failures) it like any other matcher.

When the actual value is not the kind of object a matcher needs, such as a locator passed to a page matcher or a plain string, it fails right away, without waiting, and says what it got:

```
toSee() needs a bx-playwright page or locator, but the actual value is the simple value [plain text].
toHaveTitle() needs a bx-playwright page, but the actual value is a struct.
```

## Using the Matchers Outside Browser Specs

TestBox registers the matchers for every spec of a bundle with [browser support](/browser-testing/browser-testing#turning-on-browser-support), turned on by `@browser`, `@browserProfile` or `@baseURL`. In any other BoxLang spec, register them yourself with [`addMatchers()`](/digging-deeper/expectations/custom-matchers):

```java
class extends="testbox.system.BaseSpec" {

    function beforeAll() {
        addMatchers( new testbox.system.browser.BrowserMatchers() )
    }

    function run() {
        describe( "Home page", () => {
            it( "greets visitors", () => {
                playwright().browse( ( page ) => {
                    page.visit( "http://localhost:8080/" )
                    expect( page ).toSee( "Welcome" )
                    expect( page.locator( "h1" ) ).toHaveText( "Hello" )
                } )
            } )
        } )
    }

}
```

## Beyond These Matchers

bx-playwright ships many more web-first checks: enabled, checked, focused, attributes, CSS classes, accessible names and more. Use them through `page.expect( selector )` or the inline `assert*()` methods; their `Playwright.AssertionFailed` exceptions count as TestBox failures:

```java
page.expect( "@save" ).toBeEnabled()
page.expect( "@terms" ).not().toBeChecked()
page.assertAttribute( "@avatar", "alt", "Luis" )
```

See the full list in the [bx-playwright assertions guide](https://bxplaywright.boxlang.io/assertions/).


# Attachments

Attach screenshots, traces, videos and any other file to a spec, and find them in every report.

A failing browser test is much easier to fix when you can see the page. TestBox lets any spec **attach files** to its result: screenshots, Playwright traces, videos, logs, HAR files or anything else. Reporters list the attachments under the spec, and the JUnit reports expose them to Jenkins and GitLab.

[Browser specs](/browser-testing/browser-testing#turning-on-browser-support) attach the screenshots, trace and videos of a failed `browse()` call for you, and you can call `attach()` from any spec, on any engine.

## `attach()`

```java
attach( required string path, string type = "file", string name = "" )
```

| Argument | Default       | Description                                                                                                        |
| -------- | ------------- | ------------------------------------------------------------------------------------------------------------------ |
| `path`   |               | The absolute path of the file.                                                                                     |
| `type`   | `file`        | The kind of file, for example `file`, `screenshot`, `trace`, `video` or `log`. Reporters show it next to the name. |
| `name`   | the file name | The display name. Defaults to the file name of `path`.                                                             |

`attach()` returns the spec, so calls chain. Attachments are kept for **passed and failed** specs alike.

{% tabs %}
{% tab title="BoxLang" %}
{% code title="tests/specs/ReportSpec.bx" %}

```java
class extends="testbox.system.BaseSpec" {

    function run() {
        describe( "Monthly report", () => {

            afterEach( () => {
                // Keep the application log of every spec
                attach( expandPath( "/logs/app.log" ), "log" )
            } )

            it( "renders the PDF", () => {
                var pdf = getTempDirectory() & "report.pdf"
                new models.Reports().monthly( pdf )

                attach( path = pdf, type = "file", name = "Monthly report" )
                expect( fileExists( pdf ) ).toBeTrue()
            } )

        } )
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="CFML" %}
{% code title="tests/specs/ReportSpec.cfc" %}

```cfscript
component extends="testbox.system.BaseSpec" {

    function run(){
        describe( "Monthly report", function(){

            afterEach( function(){
                // Keep the application log of every spec
                attach( expandPath( "/logs/app.log" ), "log" );
            } );

            it( "renders the PDF", function(){
                var pdf = getTempDirectory() & "report.pdf";
                new models.Reports().monthly( pdf );

                attach( path = pdf, type = "file", name = "Monthly report" );
                expect( fileExists( pdf ) ).toBeTrue();
            } );

        } );
    }

}
```

{% endcode %}
{% endtab %}
{% endtabs %}

In xUnit bundles, call `attach()` from the test method, `setup()` or `teardown()`.

{% hint style="warning" %}
`attach()` only works while a spec runs, on the thread running it: from a spec body, `beforeEach()`, `afterEach()` or `aroundEach()` (or `setup()`, a test method and `teardown()` in xUnit). Anywhere else, such as `beforeAll()` or a thread you spawned, it throws `TestBox.InvalidContext`.
{% endhint %}

TestBox records the path you give it; it does not copy the file. Keep attached files where your CI job can collect them, and do not delete them in `afterAll()` if you want to look at them later.

## Automatic Browser Artifacts

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-cc692d96ffea42c33f3428bb8907159a6f552b5d%2Ftestbox-failure-artifacts.gif?alt=media" alt="A failed browser spec with its screenshot in the HTML report and its Playwright trace"><figcaption><p>The screenshot, trace and video of a failed browser spec</p></figcaption></figure>

{% hint style="info" %}
Automatic browser artifacts require BoxLang and bx-playwright, like every [browser spec](/browser-testing/browser-testing) feature. Browser specs are BoxLang classes, and on BoxLang without bx-playwright they skip before any artifact is recorded.
{% endhint %}

bx-playwright records screenshots, traces and videos according to its **artifact policies**. They are all `off` by default. Turn them on with a profile, for example the built-in `ci` profile, or with the `artifacts` setting or `browse()` option:

| Policy                                  | Keeps                                          |
| --------------------------------------- | ---------------------------------------------- |
| `off`                                   | nothing                                        |
| `on`                                    | always                                         |
| `only-on-failure` / `retain-on-failure` | only when the browser context closes as failed |

The `ci` profile keeps a screenshot (`only-on-failure`), a trace and videos (`retain-on-failure`) of every failed context:

```java
@browserProfile( "ci" )
class extends="testbox.system.BaseSpec" {
    // ...
}
```

Or per `browse()` call:

```java
browse(
    ( page ) => {
        page.visit( "/checkout" ).click( "Pay now" )
        expect( page ).toSee( "Thank you" )
    },
    {
        artifacts : {
            screenshot : "only-on-failure",
            trace      : "retain-on-failure",
            directory  : expandPath( "/tests/results/artifacts" )
        }
    }
)
```

When the `browse()` closure throws, whether from a matcher, a bx-playwright assertion or any other error, TestBox closes each browser context as failed, attaches what the policies kept to the running spec, then rethrows the original exception:

| Kept file                   | Attachment type |
| --------------------------- | --------------- |
| Screenshot of each page     | `screenshot`    |
| Playwright trace (a `.zip`) | `trace`         |
| Video of each page          | `video`         |

This is the screenshot TestBox attached when the spec expected the last order to be `Shipped` but the page showed `Processing`:

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-796379a095bbac7394b62bac0b1ebcf50bc1230f%2Fbrowser-testing-failure-screenshot.png?alt=media" alt="Failure screenshot of the dashboard with the last order still Processing"><figcaption><p>The failure screenshot: the last order is still Processing</p></figcaption></figure>

Files go to `~/.boxlang/playwright/artifacts` unless you set `artifacts.directory`. When the closure passes, nothing is kept or attached for the `on-failure` policies. More on policies in the [bx-playwright testing guide](https://bxplaywright.boxlang.io/testing/).

### Opening a Trace

A trace records every action, a DOM snapshot before and after it, the console and the network. Open one in the Playwright trace viewer:

```bash
bxplaywright show-trace tests/results/artifacts/trace.zip
```

Select an action to see the page at that moment, the call parameters and the error. Here the `hasText` assertion waited 5 seconds for `Shipped` and the trace shows the `Processing` pill it found instead:

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0be6c18ba48e8621bd4522425770dccce493932e%2Fbrowser-testing-trace-viewer.png?alt=media" alt="The Playwright trace viewer showing the failed hasText assertion"><figcaption><p>The failed assertion in the Playwright trace viewer</p></figcaption></figure>

## Attachments in Reports

| Reporter or output                                                          | Shows                                                                                                                                                          |
| --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| JSON (`json`) and Raw                                                       | An `attachments` array of `{ path, type, name }` in every spec's stats, passed or failed.                                                                      |
| Simple (`simple`), Min (`min`), Dot (`dot`) and Doc (`doc`)                 | Screenshots as thumbnails that open full size, and a list of the other files, each name linking to its file. A trace has a **Copy show-trace command** button. |
| JUnit (`junit`) and ANT JUnit (`antjunit`)                                  | A `<system-out>` element on the test case with one `[[ATTACHMENT\|path]]` line per file.                                                                       |
| Text (`text`), Console (`console`) and the BoxLang runner `--stream` output | The attachments of **failed and errored** specs, listed under the failure with their name, type and path.                                                      |

### Screenshots in the HTML Reports

The HTML reporters embed image attachments (`png`, `jpg`, `gif` and `webp`) in the page, so the screenshot of a failure shows right on the failed spec. Click a thumbnail to see it full size, then click anywhere or press Escape to close it.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-9d0f1a426ac119bbfb1b082cd174781fcafd6573%2Fbrowser-testing-report-inline-screenshot.png?alt=media" alt="A failed browser spec in the Simple report with its screenshot as a thumbnail, and its trace and video listed below"><figcaption><p>The failure screenshot on the failed spec</p></figcaption></figure>

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-eaab71980d999fe366e673481707cd9858db630a%2Fbrowser-testing-report-screenshot-zoom.png?alt=media" alt="The failure screenshot open full size over the report"><figcaption><p>A click opens it full size</p></figcaption></figure>

Embedding means the screenshots work wherever the report goes: served by a web runner, saved as a file, or uploaded as a CI artifact. A failed spec's screenshots are embedded once, in its failure card, and the bundle list links to that card.

Images up to 2 MB are embedded. Larger ones stay links. Change the limit with the `inlineImageMaxKB` reporter option, or set it to `0` to link every image:

{% tabs %}
{% tab title="BoxLang" %}

```java
new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = { type : "simple", options : { inlineImageMaxKB : 512 } }
).run()
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
new testbox.system.TestBox(
    bundles  = "tests.specs",
    reporter = { type : "simple", options : { inlineImageMaxKB : 512 } }
).run();
```

{% endtab %}
{% endtabs %}

Videos, traces and other files are listed under the spec. A trace has a **Copy show-trace command** button that copies the `bxplaywright show-trace` command for its path.

The JUnit output follows the convention of the Jenkins [JUnit Attachments plugin](https://plugins.jenkins.io/junit-attachments/), which GitLab also reads for its test reports:

```xml
<testcase name="pays with a card" classname="tests.specs.CheckoutSpec" time="3.2">
    <failure message="Locator expected to be visible ...">...</failure>
    <system-out>[[ATTACHMENT|/builds/app/tests/results/artifacts/checkout-1.png]]
[[ATTACHMENT|/builds/app/tests/results/artifacts/trace.zip]]</system-out>
</testcase>
```

* **Jenkins:** install the JUnit Attachments plugin and publish the JUnit report. Attachments appear on each test result page.
* **GitLab:** publish the report as `artifacts:reports:junit` and keep the attached files in the job artifacts. GitLab shows screenshots on the failed test in the merge request test report. It resolves the paths inside the job artifacts, so write artifacts under the project directory, for example with `artifacts.directory`.

When you consume results programmatically, read the attachments from the spec stats:

{% tabs %}
{% tab title="BoxLang" %}

```java
var results = new testbox.system.TestBox( bundles = "tests.specs.CheckoutSpec" ).runRaw()
var spec    = results.getBundleStats()[ 1 ].suiteStats[ 1 ].specStats[ 1 ]

for ( var attachment in spec.attachments ) {
    println( "#attachment.name# (#attachment.type#): #attachment.path#" )
}
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
var results = new testbox.system.TestBox( bundles = "tests.specs.CheckoutSpec" ).runRaw();
var spec    = results.getBundleStats()[ 1 ].suiteStats[ 1 ].specStats[ 1 ];

for ( var attachment in spec.attachments ) {
    writeOutput( "#attachment.name# (#attachment.type#): #attachment.path#<br>" );
}
```

{% endtab %}
{% endtabs %}

See [Reporters](/digging-deeper/reporters) for how to choose a reporter.


# Retries

Rerun failing or erroring specs a few times before reporting them, per spec, per bundle or for the whole run.

Browser tests talk to a real browser, a real server and sometimes real third-party services, so a spec can fail once for reasons that have nothing to do with your code. **Retries** run a failing or erroring spec again, up to a number of extra times, and report the final attempt. They work for every spec, browser or not, BDD or xUnit, on every engine.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-9791ada493be88ca8cd87cff0321c9dff25280f5%2Ftestbox-spec-retries.gif?alt=media" alt="A spec with retries = 2 that passes on its second attempt"><figcaption><p>A flaky spec passing on its second attempt</p></figcaption></figure>

{% hint style="success" %}
Retries hide flakiness, they do not fix it. Prefer the web-first [browser matchers](/browser-testing/browser-matchers), which already wait, over retries, and keep the retry count low. The [attempts](#attempts-in-the-results) TestBox records tell you which specs need attention.
{% endhint %}

## How a Retry Runs

When an attempt fails or errors and attempts remain, TestBox runs the **whole spec life-cycle again**:

* BDD: every `beforeEach()`, the `aroundEach()` closures, the spec body and every `afterEach()`.
* xUnit: `setup()`, the test method (with its expected exception checks) and `teardown()`.

The spec passes as soon as one attempt passes. When every attempt fails, the spec reports the failure or error of the **last** attempt. Skipped specs (`skip()`, `xit()`, a `skip` constraint) are never retried. Files [attached](/browser-testing/attachments) during earlier attempts stay on the spec, so you keep the screenshots of every failed attempt.

## Declaring Retries

### On a spec: the `retries` argument

`it()`, `fit()` and `xit()` take a `retries` argument: how many **extra** times to run the spec. `retries = 2` means up to three attempts.

### On a bundle: the `retries` annotation

A `retries` annotation on the bundle class applies to every spec of the bundle that does not declare its own.

### On an xUnit test: the `retries` method annotation

xUnit test methods take a `retries` annotation, which wins over the bundle annotation.

{% tabs %}
{% tab title="BDD - BoxLang" %}
{% code title="tests/specs/CheckoutSpec.bx" %}

```java
// Every spec of this bundle gets one retry
@browser
@retries( 1 )
class extends="testbox.system.BaseSpec" {

    function run() {
        describe( "Checkout", () => {

            // Uses the bundle retries: up to 2 attempts
            it( "shows the cart", () => {
                browse( ( page ) => {
                    expect( page.visit( "/cart" ) ).toSee( "Your cart" )
                } )
            } )

            // The spec value wins: up to 4 attempts
            it(
                title   = "pays with the sandbox gateway",
                body    = () => {
                    browse( ( page ) => {
                        page.visit( "/checkout" ).click( "Pay now" )
                        expect( page ).toSee( "Thank you" )
                    } )
                },
                retries = 3
            )

        } )
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="xUnit - BoxLang" %}
{% code title="tests/specs/CheckoutTest.bx" %}

```groovy
// Every test of this bundle gets one retry
@browser
@retries( 1 )
class extends="testbox.system.BaseSpec" {

    // Uses the bundle retries: up to 2 attempts
    function testShowsTheCart() {
        browse( ( page ) => {
            expect( page.visit( "/cart" ) ).toSee( "Your cart" )
        } )
    }

    // The method annotation wins: up to 4 attempts
    @retries( 3 )
    function testPaysWithTheSandboxGateway() {
        browse( ( page ) => {
            page.visit( "/checkout" ).click( "Pay now" )
            expect( page ).toSee( "Thank you" )
        } )
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="BDD - CFML" %}
{% code title="tests/specs/PaymentGatewaySpec.cfc" %}

```cfscript
// Every spec of this bundle gets one retry
component extends="testbox.system.BaseSpec" retries="1" {

    function run(){
        describe( "Payment gateway", function(){

            // Uses the bundle retries: up to 2 attempts
            it( "pings the sandbox", function(){
                expect( new models.Gateway().ping() ).toBeTrue();
            } );

            // The spec value wins: up to 4 attempts
            it(
                title   = "charges a card in the sandbox",
                body    = function(){
                    var charge = new models.Gateway().charge( 100 );
                    expect( charge.status ).toBe( "succeeded" );
                },
                retries = 3
            );

        } );
    }

}
```

{% endcode %}
{% endtab %}

{% tab title="xUnit - CFML" %}
{% code title="tests/specs/PaymentGatewayTest.cfc" %}

```cfscript
// Every test of this bundle gets one retry
component extends="testbox.system.BaseSpec" retries="1" {

    // Uses the bundle retries: up to 2 attempts
    function testPingsTheSandbox(){
        $assert.isTrue( new models.Gateway().ping() );
    }

    // The method annotation wins: up to 4 attempts
    function testChargesACardInTheSandbox() retries="3"{
        var charge = new models.Gateway().charge( 100 );
        $assert.isEqual( "succeeded", charge.status );
    }

}
```

{% endcode %}
{% endtab %}
{% endtabs %}

### For the whole run: the `retries` option

Give every spec that declares nothing a default with the `retries` runner option. On the [BoxLang CLI runner](/getting-started/running-tests/boxlang-cli-runner):

```bash
./testbox/run --directory=tests.specs --retries=2
```

Or through the `options` of `TestBox` when you run tests from code:

{% tabs %}
{% tab title="BoxLang" %}

```java
var testbox = new testbox.system.TestBox(
    directory = "tests.specs",
    options   = { retries : 2 }
)
println( testbox.run( reporter = "text" ) )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
var testbox = new testbox.system.TestBox(
    directory = "tests.specs",
    options   = { retries : 2 }
);
writeOutput( testbox.run( reporter = "simple" ) );
```

{% endtab %}
{% endtabs %}

## Precedence

TestBox resolves the retries of a spec in this order, and the first match wins:

| Order | Source                                                                      | Notes                                                                                                                                          |
| ----- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| 1     | The spec: `it( ..., retries = N )` or the xUnit `retries` method annotation | Only when greater than `0`. `0`, the default, means "inherit".                                                                                 |
| 2     | The bundle `retries` annotation                                             | Any number, so `@retries( 0 )` (or `retries="0"` on a CFML component) turns retries off for the bundle, even when the run sets a global value. |
| 3     | The global `retries` runner option (`--retries=N`)                          | Applies to specs and bundles that declare nothing.                                                                                             |
| 4     | None                                                                        | `0`: every spec runs once.                                                                                                                     |

## Attempts in the Results

Every spec records how many times it ran in the `attempts` key of its stats: `1` for a spec that ran once, more for a retried spec. Reporters call out specs that needed more than one attempt, for example in the text reporter:

```
( √ ) shows the cart (182 ms)
( √ ) pays with the sandbox gateway (4210 ms) (passed after 2 attempts)
( X ) charges a card in the sandbox (9033 ms) (failed after 4 attempts)
```

The text, console and Simple reporters and the BoxLang runner `--stream` output show the note. The JSON and Raw reports carry `attempts` for every spec, so your CI can flag flaky specs:

{% tabs %}
{% tab title="BoxLang" %}

```java
var results = new testbox.system.TestBox( directory = "tests.specs", options = { retries : 2 } ).runRaw()

var flaky = []
var collect = ( suites ) => {
    for ( var suite in suites ) {
        flaky.append( suite.specStats.filter( ( spec ) => spec.status == "Passed" && spec.attempts > 1 ), true )
        collect( suite.suiteStats )
    }
}
for ( var bundle in results.getBundleStats() ) {
    collect( bundle.suiteStats )
}
println( "Flaky specs: " & flaky.map( ( spec ) => spec.name ).toList( ", " ) )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
var results = new testbox.system.TestBox( directory = "tests.specs", options = { retries : 2 } ).runRaw();

var flaky   = [];
var collect = function( suites ){
    for ( var suite in suites ) {
        arrayAppend( flaky, suite.specStats.filter( function( spec ){
            return spec.status == "Passed" && spec.attempts > 1;
        } ), true );
        collect( suite.suiteStats );
    }
};
for ( var bundle in results.getBundleStats() ) {
    collect( bundle.suiteStats );
}
writeOutput( "Flaky specs: " & flaky.map( function( spec ){ return spec.name; } ).toList( ", " ) );
```

{% endtab %}
{% endtabs %}

## Retries and `--failed`

Retries handle a hiccup inside one run. To rerun only what failed after the run is over, use the BoxLang runner [`--failed`](/browser-testing/running-browser-tests#rerun-what-failed-failed) option. The two combine well: `./testbox/run --failed --retries=1`.


# Running Browser Tests

Start your web server for the run, rerun only what failed, and run browser tests in CI.

Browser specs are regular TestBox bundles, so every [runner](/getting-started/running-tests) can run them. The [BoxLang CLI runner](/getting-started/running-tests/boxlang-cli-runner) adds options that make browser test runs smooth: it can start your application before the tests and stop it afterwards, rerun only what failed last time, and retry flaky specs.

```bash
./testbox/run --directory=tests.browser \
    --web-server="boxlang-miniserver --port 8080" \
    --retries=1
```

## BoxLang Runner Options

| Option                 | Default                 | Description                                                                                      |
| ---------------------- | ----------------------- | ------------------------------------------------------------------------------------------------ |
| `--web-server`         |                         | A shell command that starts a web server before the tests run.                                   |
| `--web-server-url`     | `http://localhost:8080` | The URL polled until the server answers. Also the default `baseURL` of browser bundles.          |
| `--web-server-timeout` | `60`                    | How long to wait for the server to answer, in seconds.                                           |
| `--retries`            | `0`                     | How many extra times to run a failing or erroring spec. See [Retries](/browser-testing/retries). |
| `--failed`             | `false`                 | Run only the bundles and specs that failed or errored in the last run.                           |

`--retries` and `--failed` work for any bundle, `.bx` or `.cfc`, browser test or not.

## Start a Web Server for the Run

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-fc2b174a7997b1ffce4ac7a82b60cedfed0f024c%2Ftestbox-web-server.gif?alt=media" alt="The BoxLang runner starting a MiniServer, running a browser spec and stopping the server"><figcaption><p>The BoxLang runner starting and stopping your web server</p></figcaption></figure>

Browser tests need your application running. With `--web-server`, the runner starts it for you:

1. It runs the command with `sh -c` (`cmd /c` on Windows) from the directory you run the tests from.
2. It polls `--web-server-url` until the server answers with an HTTP status below 500.
3. It stores the URL in `server.testbox.webServerURL`, which every [browser bundle](/browser-testing/browser-testing#bundle-annotations) without a `baseURL` annotation uses as its base URL, so `page.visit( "/login" )` just works.
4. It runs the tests.
5. It stops the server **and its child processes** after the tests, whether they passed, failed or threw.

```bash
# BoxLang MiniServer on the default port
./testbox/run --web-server="boxlang-miniserver --port 8080"

# Any other server, on another port
./testbox/run --web-server="box server start port=8500 --console" --web-server-url=http://localhost:8500 --web-server-timeout=120
```

If the server does not answer within `--web-server-timeout` seconds, or its command exits first, the runner stops it, prints the reason with the command and the last lines it printed, and **exits with code 1** without running the tests.

{% hint style="warning" %}
**Quoting the command.** Always quote a `--web-server` command that contains spaces. Some BoxLang launchers split quoted arguments at their spaces before the runner sees them, so the runner rebuilds the command: every word after `--web-server=` belongs to the command until the next TestBox runner option (such as `--directory` or `--retries`). A command whose own flags share the name of a runner option, for example a server that takes `--directory`, would be cut short there: put it in a script and pass the script instead.

```bash
# bin/start-server.sh holds: my-server --directory ./www --port 8080
./testbox/run --web-server="./bin/start-server.sh"
```

{% endhint %}

Prefer to start the server yourself? Skip `--web-server` and set the `baseURL` annotation on your bundles, or the `BX_PLAYWRIGHT_BASEURL` environment variable.

## Rerun What Failed: `--failed`

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-2124c3f1742a323094cb6cba695361f5119d04a2%2Ftestbox-run-failed.gif?alt=media" alt="The Run Failed button of the HTML report and ./testbox/run --failed rerunning one spec"><figcaption><p>Run Failed in the report and --failed in the CLI</p></figcaption></figure>

Every run of the BoxLang runner writes a `.testbox-failed.json` file to the report path (`--reportpath`, `tests/results` by default) with the bundles and spec ids that failed or errored:

```json
{ "bundles" : [ "tests.specs.LoginSpec" ], "specs" : [ "spec id", "spec id" ], "bundleErrors" : [ "tests.specs.CartSpec" ] }
```

`--failed` reads that file and runs only those bundles and specs:

```bash
# Full run: 3 specs fail
./testbox/run --directory=tests.specs

# Fix the code, then rerun just the 3 failures
./testbox/run --failed
```

* A bundle that failed outside of a spec, for example in `beforeAll()` or `afterAll()`, is broken, not flaky: it goes to `bundleErrors` and is **not** rerun. `--failed` lists those bundles so you can fix them and run them directly. The other failed bundles still rerun only their failed specs.
* When everything passed, every array is empty. `--failed` then prints `No failed tests recorded in [...], nothing to run.` and runs nothing. The same happens when the file is missing.
* The rerun writes the file again, so repeat `--failed` until it has nothing left to run.
* Use the same `--reportpath` for the full run and the rerun.

Combine it with [retries](/browser-testing/retries) for a forgiving rerun: `./testbox/run --failed --retries=1`.

### Run Failed in the HTML reports

The web runners keep no state, so they need no file. When something failed, the Simple, Min, Dot and Doc reports show a **Run Failed (N)** button next to **Run All**. Its link is built from the report on screen: `?testBundles=...&testSpecs=...` with the failed bundles and spec ids. Click it, fix, click it again. When the spec ids would make the link too long, it reruns the failed bundles whole. Bundles that failed outside of a spec are left out, like with `--failed`.

### From code

Both use `TestResult.getFailedTargets()`, available on every engine:

```js
var results = new testbox.system.TestBox( directory = "tests.specs" ).runRaw()
var failed  = results.getFailedTargets()
// { bundles : [ "tests.specs.LoginSpec" ], specs : [ "spec id" ], bundleErrors : [] }

new testbox.system.TestBox( bundles = failed.bundles ).runRaw( testBundles = failed.bundles, testSpecs = failed.specs )
```

## Debugging a Failing Browser Spec

* Run the bundle with a visible browser: annotate the bundle with `@browserProfile( "debug" )`, or run with `BX_PLAYWRIGHT_PROFILE=debug` when the bundle has no `browserProfile`. The `debug` profile is headed, slowed down and records every artifact.
* Open the trace a failure [attached](/browser-testing/attachments) with `bxplaywright show-trace path/to/trace.zip`. It shows every action, the page before and after it, the console and the network.
* Record the steps of a new spec as BoxLang code with `bxplaywright codegen http://localhost:8080`.

<figure><img src="https://2482745662-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F5kuiG5ZXNT2hNA83299A%2Fuploads%2Fgit-blob-0be6c18ba48e8621bd4522425770dccce493932e%2Fbrowser-testing-trace-viewer.png?alt=media" alt="The Playwright trace viewer showing the failed hasText assertion"><figcaption><p>Debugging a failure in the Playwright trace viewer</p></figcaption></figure>

More in the [bx-playwright testing guide](https://bxplaywright.boxlang.io/testing/).

## Continuous Integration

A CI run needs the bx-playwright module, a browser and its system libraries, your application running, and somewhere to keep the screenshots and traces of failed specs:

* Install the browser with `bxplaywright install chromium --with-deps` (the `--with-deps` flag installs the system libraries on Linux).
* Use the `ci` profile, through `BX_PLAYWRIGHT_PROFILE=ci` or a `@browserProfile( "ci" )` annotation: headless, with a screenshot, trace and videos kept for every failed context.
* Cache `~/.boxlang/playwright` (driver, Node.js and browsers) between runs.
* Start the application with `--web-server`.
* Upload `tests/results` and the artifacts when the job fails.

### GitHub Actions

A complete workflow: it installs BoxLang with bx-playwright, installs TestBox with CommandBox, caches the browsers, runs the tests against the BoxLang MiniServer with one retry, and uploads the reports, screenshots, traces and videos of failed tests.

{% code title=".github/workflows/browser-tests.yml" %}

```yaml
name: Browser Tests

on: [ push, pull_request ]

jobs:
  browser-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: "21"

      - uses: ortus-boxlang/setup-boxlang@main
        with:
          version: latest
          modules: bx-playwright

      # Installs TestBox and your other dependencies from box.json
      - uses: Ortus-Solutions/setup-commandbox@main

      - name: Install dependencies
        run: box install

      # Driver, Node.js and browsers: one download per bx-playwright version
      - name: Read the bx-playwright version
        id: pw
        run: echo "version=$( jq -r .version ~/.boxlang/modules/bx-playwright/box.json )" >> "$GITHUB_OUTPUT"

      - uses: actions/cache@v4
        with:
          path: ~/.boxlang/playwright
          key: playwright-${{ runner.os }}-${{ steps.pw.outputs.version }}

      # --with-deps installs the system libraries, which are not cached
      - name: Install Chromium
        run: |
          export PATH="$HOME/.boxlang/bin:$PATH"
          bxplaywright install chromium --with-deps
          bxplaywright doctor

      - name: Run browser tests
        env:
          BX_PLAYWRIGHT_PROFILE: ci
        run: |
          export PATH="$HOME/.boxlang/bin:$PATH"
          ./testbox/run --directory=tests.specs \
            --web-server="boxlang-miniserver --port 8080" \
            --web-server-url=http://localhost:8080 \
            --retries=1

      - name: Upload reports and failure artifacts
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: browser-test-results
          path: |
            tests/results
            ~/.boxlang/playwright/artifacts
          if-no-files-found: ignore
```

{% endcode %}

Adapt the run step to your project: point `--directory` at your specs, and replace the MiniServer command with whatever starts your application. Artifacts go to `~/.boxlang/playwright/artifacts` unless you set the bx-playwright `artifacts.directory` setting. Download the `browser-test-results` artifact from the failed run and open a trace with `bxplaywright show-trace trace.zip`.

### Jenkins and GitLab

Run with `--reporter=junit` and publish `tests/results` as a JUnit report. Each test case lists its attachments in `<system-out>` as `[[ATTACHMENT|path]]` lines, which the Jenkins JUnit Attachments plugin and GitLab test reports pick up. See [Attachments in Reports](/browser-testing/attachments#attachments-in-reports).

See [Continuous Integration](/digging-deeper/ci) for more CI setups.


# MockBox

Create mocks and stubs!

![MockBox](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/AY6J6xo3PfNzYas2YsqN/MockBox_300.png)

## Introduction

TestBox includes a mocking and stubbing library we lovingly call MockBox. You don't have to install it or have a separate libary, it is part of TestBox.

MockBox shines by allowing you to create mock and stub objects.

### Important Setup

Write capabilities on disk for the default path of `/testbox/system/testings/stubs`.

You can also choose the directory destination for stub creations yourself when you initialize TestBox. If using ColdFusion 9 or Lucee you can even use `ram://` and use the virtual file system.

## Useful Resources

* [Approaches to Mocking](http://www.onjava.com/pub/a/onjava/2004/02/11/mocks.html)
* [Wikipedia Mock Objects](http://en.wikipedia.org/wiki/Mock_object)
* [Using mock objects for complex unit tests IBM developerWorks](http://www-128.ibm.com/developerworks/rational/library/oct06/pollice/index.html)
* [Unit testing with mock objects IBM developerWorks](http://www.ibm.com/developerworks/library/j-mocktest.html)
* [Emergent Design by Scott Bain](http://www.netobjectives.com/emergent-design-evolutionary-nature-professional-software-development)
* [Mocks Aren't Stubs by Martin Fowler](http://martinfowler.com/articles/mocksArentStubs.html)


# What is Mocking?

> "A mock object is an object that takes the place of a 'real' object in such a way that makes testing easier and more meaningful, or in some cases, possible at all". by Scott Bain (**Emergent Design**\
> [The Evolutionary Nature of Professional Software Development](http://www.netobjectives.com/resources/books/emergent-design))

Here are some examples of real life mocks to get you in the mocking mood:

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/NTaHSlavYEk4KKYBm3qA/mockbox_nikemock.jpg)

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/CezbyjD8dR0LUKurrW5z/mockbox_pumamock.jpg)

When doing unit testing of ColdFusion CFCs, we will come to a point where a single class can have multiple external dependencies or collaborators; whether they are classes themselves, data, external APIs, etc. Therefore, in order to unit test our class exclusively and easily we need to be able to mock this behavior or have full control of this behavior. Remember that unit testing is the testing of software units in isolation. If not, we would be instantiating and creating entire set of components, frameworks, pulling network plugs and so much more ridiculous but functional things just to test one single piece of functionality and/or behavior. So in summary, mock objects are just test oriented replacements for collaborators and dependencies.

Mock objects can also be created by hand, but MockBox takes this pain away by leveraging dynamic techniques so that you can Mock dynamically and at runtime. Like [Scott Bain](http://www.netobjectives.com/about/coaches/20) describes in his [Emergent Design](http://www.amazon.com/Emergent-Design-Evolutionary-Professional-Development/dp/0321509366) book:

> "Mocks are definitely congruent with the Gang of Four (GoF) notion of designing to interfaces, because a mock is essentially the interface without any real implementation." - Scott Bain (Emergent Design)

You will be leveraging MockBox to create objects that represent your dependencies or even data, decide what methods will return (expectations), mock network connections, exceptions and much more. You can then very easily test the exclusive behavior of components as you will now have control of all expectations, and remember that testing is all about expectations. Also, as your object oriented applications get more complex, mocking becomes essential, but you have to be aware that there are limitations. Not only will you do unit-testing but you will need to expand to do integration testing to make sure the all encompassing behavior is still maintained. However, by using a mocking framework like MockBox you will be able to apply a test-driven development methodology to your unit-testing and be able to accelerate your development and testing. The more you mock, the more you will get a feel for it and find it completely essential when doing unit testing. Welcome to a world where mocking is fun and not frowned upon :)


# Our Approach and Benefits

The approach that we take with MockBox is a dynamic and minimalistic approach. Why dynamic? Well, because we dynamically transform target objects into mock form at runtime. The API for the mocking factory is very easy to use and provides you a very simplistic approach to mocking.

We even use `$()style` method calls so you can easily distinguish when using or mocking methods, properties, etc. So what can MockBox do for me?

* Create mock objects for you and keep their methods intact (Does not wipe methods, so you can do method spys, or mock helper methods)
* Create mock objects and wipe out their method signatures
* Create stub objects for objects that don't even exist yet. So you can build to interfaces and later build dependencies.
* Decorate instantiated objects with mocking capabilities (So you can mock targeted methods and properties; spys)
* Mock internal object properties, basically do property injections in any internal scope
* State-Machine Results. Have a method recycle the results as it is called consecutively. So if you have a method returning two results and you call the method 4 times, the results will be recycled: 1,2,1,2
* Method call counter, so you can keep track of how many times a method has been called
* Method arguments call logging, so you can keep track of method calls and their arguments as they are called. This is a great way to find out what was the payload when calling a mocked method
* Ability to mock results depending on the argument signatures sent to a mocked method with capabilities to even provide state-machine results
* Ability to mock private/package methods
* Ability to mock exceptions from methods or make a method throw a controlled exception
* Ability to change the return type of methods or preserve their signature at runtime, extra cool when using stubs that still have no defined signature
* Ability to call a debugger method ($debug()) on mocked objects to retrieve extra debugging information about its mocking capabilities and its mocked calls


# Creating MockBox

```javascript
mockBox = new testbox.system.MockBox();

// Within a TestBox Spec
getMockBox()
```

The factory takes in one constructor argument that is not mandatory: `generationPath`. This path is a relative path of where the factory generates internal mocking stubs that are included later on at runtime. Therefore, the path must be a path that can be used using `cfinclude`. The default path the mock factory uses is the following, so you do not have to specify one, just make sure the path has WRITE permissions:

```javascript
/testbox/system/stubs
```

> **Hint** If you are using Lucee or ACF10+ you can also decide to use the `ram://` resource and place all generated stubs in memory.


# Creating a Mock Object

In order to create a mock object you need to use any of the following methods: `createMock()`, `createEmptyMock()`, or `prepareMock()`.

## createMock()

Used to create a new mock object from scratch or from an already instantiated object.

```javascript
public any createMock([string CLASSNAME], [any OBJECT], [boolean CLEARMETHODS='false'], [boolean CALLLOGGING='true'])
```

Parameters:

* className - The class name of the object to create and mock
* object - The instantiated object to add mocking capabilities to, similar to using prepareMock()
* clearMethods - If true, all methods in the target mock object will be removed. You can then mock only the methods that you want to mock
* callLogging - Add method call logging for all mocked methods only

```javascript
collaborator = mockbox.createMock("model.myClass");
```

## createEmptyMock()

Used to create a new mock object with all its method signatures wiped out, basically an interface with no real implementation. It will be up to you to mock all behavior.

```javascript
public any createEmptyMock(string CLASSNAME, [any OBJECT], [boolean CALLLOGGING='true'])
```

Parameters:

* className - The class name of the object to create and mock
* object - The instantiated object to add mocking capabilities to, similar to using prepareMock()
* callLogging - Add method call logging for all mocked methods only

```javascript
user = mockbox.createEmptyMock("model.User");
```

## prepareMock()

Decorate an already instantiated object with mocking capabilities. It does not wipe out the object's methods or signature, it only decorates it (mixes-in methods) with methods for mocking operations. This is great for doing targeted mocking for specific methods, private methods, properties and more.

```javascript
public any prepareMock([any OBJECT], [boolean CALLLOGGING='true'])
```

Parameters:

* object - The already instantiated object to prepare for mocking
* callLogging - Add method call logging for all mocked methods only

```
myService = createObject("component","model.services.MyCoolService").init();
// prepare it for mocking
mockBox.prepareMock( myService );
```

> **Caution** If call logging is turned on, then the mock object will keep track of all method calls to mocked methods ONLY. It will store them in a sequential array with all the arguments the method was called with (named or ordered). This is essential if you need to investigate if a method was called and with what arguments. You can also use this to inspect save or update calls based on mocked external repositories.

\
**Sample:**

![](https://content.gitbook.com/content/5kuiG5ZXNT2hNA83299A/blobs/GvzeBpUYLuFEwzXrKcFl/mockbox_UserServiceSample.png)

Let's say that we have a user service layer object that relies on the following objects:

* **sessionstorage** - a session facade object
* **transfer** - the transfer ORM
* **userDAO** - a data access object for complex query operations

We can start testing our user service and mocking its dependencies by preparing it in a test case CFC with the following `setup()` method:

```javascript
component extends=”testbox.system.BaseSpec” {

    function beforeAll(){
        //Create the User Service to test, do not remove methods, just prepare for mocking.
        userService = createMock("model.UserService");

        // Mock the session facade, I am using the coldbox one, it can be any facade though
        mockSession= createEmptyMock(className='coldbox.system.plugins.SessionStorage');

        // Mock Transfer
        mockTransfer = createEmptyMock(className='transfer.com.Transfer');

        // Mock DAO
        mockDAO = createEmptyMock(className='model.UserDAO');

        //Init the User Service    with mock dependencies
        userService.init(mockTransfer,mockSession,mockDAO);
    }

    function run(){

        describe( "User Service", function(){
            it( "can get data", function(){
                // mock a query using mockbox's querysimulator
                mockQuery = querySim("id, name
                1|Luis Majano
                2|Alexia Majano");
                // mock the DAO call with this mocked query as its return
                mockDAO.$("getData", mockQuery);

                data = userService.getData();
                expect( data ).toBe( mockQuery );
            });
        });

    }

}
```

The service CFC we just injected mocked dependencies:

```javascript
<cfcomponent name="UserService" output="False">

<cffunction name="init" returntype="UserService" output="False">
  <cfargument name="transfer">
  <cfargument name="sessionStorage">
  <cfargument name="userDAO">
  <cfscript>
    instance.transfer = arguments.transfer;
    instance.sessionStorage = arguments.sessionStorage;
    instance.userDAO = arguments.userDAO;

    return this;
  </cfscript>
</cffunction>

<cffunction name="getData" returntype="query" output="false">
    <cfreturn instance.userDao.getData()>
</cffunction>

</cfcomponent>
```


# Creating a Stub Object

In order to create a stub object you will use the : `createStub()` method.

`public any createStub([boolean callLogging='true'], [extends], [implements])`

Parameters:

* `callLogging` - Add method call logging for all mocked methods
* `extends` - Make the stub extend from certain CFC
* `implement` - Make the stub adhere to an interface(s)

This method will create an empty stub object that you can use and mock with methods and properties. It can then be used in any code to satisfy dependencies meanwhile you build them. This is great to start working on projects where you are relying on other teams to build functionality but you have agreed on specific data or code interfaces. It is also super fancy as it can allow you to tell the stub to inherit from another CFC and look like it, or even pass in one or more interfaces that it must implement. If they are interfaces, then MockBox will generate all the necessary methods to satisfy those interfaces.

## CreateStub() Inheritance

The `createStub()` method has an argument called `extends` that accepts a class path. This will create and generate a stub that physically extends that class path directly. This is an amazing way to create stubs that you can override with inherited functionality or just make it look like it is EXACTLY the type of object you want.

```javascript
myService = mockbox.createStub(extends="model.security.MyService");
```

## CreateStub() Interfaces

The `createStub()` method has an argument called `implements` that accepts a list of interface class paths you want the stub to implement. MockBox will then generate the stub and it will make sure that it implements all the methods the interfaces have defined as per their contract. This is such a fantastic and easy way to create a stub that looks and feels and actually has the methods an interface needs.

```javascript
myFakeProvider = mockbox.createStub(implements="coldbox.system.cache.ICacheProvider");
myFakeProvider.getName();
```


# Mocking Methods

Come mock with me!

Once you have created a mock object, you can use it like the real object, which will respond exactly as it was coded. However, you can override its behavior by using the mocking methods placed on the mocked object at run-time. The methods that you can call upon in your object are the following (we will review them in detail later):

<table data-header-hidden><thead><tr><th>Method Name</th><th width="148.33333333333331">Return Type</th><th>Description</th></tr></thead><tbody><tr><td>Method Name</td><td>Return Type</td><td>Description</td></tr><tr><td><code>$()</code></td><td>Object</td><td>Used to mock a method on the mock object that can return, throw or be a void method.</td></tr><tr><td><code>$args()</code></td><td>Object</td><td>Mock 1 or more arguments in sequential or named order. Must be called concatenated to a $() call and must be followed by a concatenated $results() call so the results are matched to specific arguments.</td></tr><tr><td><code>$getProperty(name, scope)</code></td><td>any</td><td>Retrieve any public or private internal state variable so you can do assertions and more mocking.</td></tr><tr><td><code>$property()</code></td><td>Object</td><td>Mock a property in the object on any scope.</td></tr><tr><td><code>querySim()</code></td><td>query</td><td>to denote columns. Ex: id, name 1 Luis Majano 2 Joe Louis</td></tr><tr><td><code>$results()</code></td><td>Object</td><td>Mock 1 or more results of a mock method call must be chained to a $() or $().$args() call</td></tr><tr><td><code>$spy( method )</code></td><td>Object</td><td>Spy on a specific method to check how often it has been called and with what arguments and results.</td></tr><tr><td><p><code>$throws(</code></p><p><code>type,</code></p><p><code>message,</code></p><p><code>datail,</code></p><p><code>errorcode</code></p><p><code>)</code></p></td><td>Object</td><td>This method tells MockBox that you want to mock a method that will throw an exception when called.</td></tr></tbody></table>


# $() Method

This is the method that you will call upon in order to mock a method's behavior and return results. This method has the capability of mocking a return value or even making the method throw a controlled exception. By default the mocked method results will be returned all the time the method is called. So if the mocked method is called twice, the results will always be returned.

```javascript
any $(string method, [any returns], boolean preserveReturnType='true', [boolean throwException='false'], [string throwType=''], [string throwDetail=''], [string throwMessage=''], [boolean callLogging='false'], [boolean preserveArguments='false'], [any callback])
```

Parameters:

* `method` - The method you want to mock or spy on
* `returns` - The results it must return, if not passed it returns void or you will have to do the mockResults() chain
* `preserveReturnType` - If false, the mock will make the returntype of the method equal to ANY
* `throwException` - If you want the method call to throw an exception
* `throwType` - The type of the exception to throw
* `throwDetail` - The detail of the exception to throw
* `throwMessage` - The message of the exception to throw
* `callLogging` - Will add the machinery to also log the incoming arguments to each subsequent calls to this method
* `preserveArguments` - If true, argument signatures are kept, else they are ignored. If true, BEWARE with $args() matching as default values and missing arguments need to be passed too.
* `callback` - A callback to execute that should return the desired results, this can be a UDF or closure. It also receives all caller arguments as well.
* `throwErrorCode` - The error code to throw in the exception

The cool thing about this method is that it also returns the same instance of the object. Therefore, you can use it to chain calls to the object and do multiple mocking of methods all within the same line. Remember that if no returns argument is provided then the return is void

```javascript
function beforeAll(){
    mockUser = createMock("model.security.User");

    //Mock several methods all in one shot!
    mockUser.$("isFound",false).$("isDirty",false).$("isSaved",true);
}
```

## Examples

Let's do some samples now

```javascript
//make exists return true in a mocked session object
mockSession.$(method="exists",returns=true);
expect(mockSession.exists('whatevermanKey')).toBeTrue();

//make exists return true and then false and then repeat the sequence
mockSession.$(method="exists").$results(true,false);
expect( mockSession.exists('yeaaaaa') ).toBeTrue();
expect( mockSession.exists('nada') ).toBeFalse();

//make the getVar return a mock User object
mockUser = createMock(className="model.User");
mockSession.$(method="getVar",results=mockUser);

expect( mockSession.getVar('sure') ).toBe( mockUser );

//Make the call to user.checkPermission() throw an invalid exception
mockUser.$(method="checkPermission",
        throwException=true,
        throwType="InvalidPermissionException",
        throwMessage="Invalid permission detected",
        throwDetail="The permission you sent was invalid, please try again.");

try{
    mockUser.checkPermission('invalid');
}
catch(Any e){
    if( e.type neq "InvalidPermissionException"){
      fail('The type was invalid #e.type#');
    }
}

//mock a method with call logging
mockSession.$(method="setVar",callLogging=true);
mockSession.setVar("Hello","Luis");
mockSession.setVar("Name","luis majano");
//dump the call logs
<cfdump var="#mockSession.$callLog()#">
```


# $args() Method

This method is used to tell MockBox that you want to mock a method with a SPECIFIC number of argument calls. Then you will have to set the return results for it, but this is absolutely necessary if you need to test an object that makes several method calls to the same method with different arguments, and you need to mock different results coming back. Example, let's say you are using a ColdBox configuration bean that holds configuration data. You make several calls to the `getKey()` method with different arguments:

```javascript
configBean.getKey('DebugMode');
configBean.getKey('OutgoingMail');
```

How in the world can I mock this? Well, using the mock arguments method.

```javascript
//get a mock config bean
mockConfig = getMockBox().createEmptyMock("coldbox.system.beans.ConfigBean");
//mock the method for positional arguments
mockConfig.$("getKey").$args("debugmode").$results(true);
mockConfig.$("getKey").$args("OutgoingMail").$results('devmail@mail.com');

//Then you can call and get the expected results
```

> **Hint** So remember that if you use the `$args()` call, you need to tell it what kind of results you are expecting by calling the `$results()` method after it or you might end up with an exception.

If the method you are mocking is called using named arguments then you can mock this using:

```javascript
//get a mock config bean
mockConfig = getMockBox().createEmptyMock("coldbox.system.beans.ConfigBean");
//mock the method for named arguments
mockConfig.$("getKey").$args(name="debugmode").$results(true);
```

## Matching Complex Arguments

`$args()` matches structurally, so a struct argument matches whatever order its keys were built in:

{% tabs %}
{% tab title="BoxLang" %}

```java
mockService.$( "charge" )
    .$args( { amount : 100, currency : "USD" } )
    .$results( true )

// matches, despite the different key order at the call site
mockService.charge( { currency : "USD", amount : 100 } )
```

{% endtab %}

{% tab title="CFML" %}

```cfscript
mockService.$( "charge" )
    .$args( { amount : 100, currency : "USD" } )
    .$results( true );

// matches, despite the different key order at the call site
mockService.charge( { currency : "USD", amount : 100 } );
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Before TestBox 7.1, nested structures were hashed in a way that depended on struct iteration order, so two structurally-equal structs built in a different order could fail to match and the mock would return `null` instead. This was always latent but became reproducible on Lucee 7.1, which changed its underlying map implementation. Upgrade to 7.1 or later if you mock methods that take struct arguments.
{% endhint %}

As of TestBox 7.1, `$args()` also understands BoxLang `Set` and `Range` objects when matching:

{% hint style="info" %}
`Set` and `Range` argument matching requires BoxLang. On CFML engines these types do not exist, so the rest of `$args()` behaves as documented above.
{% endhint %}

```java
mockService.$( "grant" )
    .$args( setOf( "admin", "editor" ) )
    .$results( true )

mockService.$( "paginate" )
    .$args( 1..10 )
    .$results( results )
```


# $getProperty() Method

This method can help you retrieve any public or private internal state variable so you can do assertions. You can also pass in a scope argument so you can not only retrieve properties from the variables scope but from any nested structure inside of any private scope:

```javascript
any $getProperty(name [scope='variables']
```

Parameters:

* name - The name of the property to retrieve
* scope - The scope where the property lives in. The default is variables scope.

```javascript
expect( model.$getProperty("dataNumber", "variables") ).toBe( 4 );
expect( model.$getProperty("name", "variables.instance") ).toBe(  "Luis" );
```


# $property() Method

This method is used in order to mock an internal property on the target object. Let's say that the object has a private property of userDAO that lives in the variables scope and the lifecycle for the object is controlled by its parent, in this case the user service. This means that this dependency is created by the user service and not injected by an external force or dependency injection framework. How do we mock this? Very easily by using the $property() method on the target object.

```javascript
any $property(string propertyName, [string propertyScope='variables'], any mock)
```

Parameters:

* propertyName - The name of the property to mock
* propertyScope - The scope where the property lives in. The default is variables scope.
* mock - The object or data to inject and mock

```javascript
//decorate our user service with mocking capabilities, just to show a different approach
userService = getMockBox().prepareMock( createObject("component","model.UserService") );

//create a mock dao and mock the getUsers() method
mockDAO=getMockBox().createEmptyMock("model.UserDAO").$("getUsers",QueryNew(""));

//Inject it as a property of the user service, since no external injections are found. variables scope is the default.
userService.$property(propertyName="userDAO",mock=mockDAO);

//Test a user service method that uses the DAO
results = userService.getUsers();
assertTrue( isQuery(results) );
```

Not only can you mock properties that are objects, but also mock properties that are simple/complex types. Let's say you have a property in your target object that controls debugging and by default the property is false, but you want to test the debugging capabilities of your class. So we have to mock it to true now, but the property exists in variables.instance.debugMode? No problem mate (Like my friend Mark Mandel says)!

```javascript
//decorate the cache object with mocking capabilties
cache = getMockBox().createMock(object=createObject("component","MyCache"));

//mock the debug property
cache.$property(propertyName="debugMode",propertyScope="instance",mock=true);
```


# $querySim() Method

This method is NOT injected into mock objects but avaialble via MockBox directly in order to create queries very quickly. This is a great way to simulate cfquery calls, cfdirectory or any other cf tag that returns a query.

```javascript
function testGetUsers(){
    // Mock a query
    mockQuery = mockBox.querySim("id,fname,lname
    1 | luis | majano
    2 | joe | louis
    3 | bob | lainez");

    // tell the dao to return this query
    mockDAO.$("getUsers", mockQuery);
}
```


# $results() Method

This method can only be used in conjunction with `$()` as a chained call as it needs to know for what method are the results for.

```javascript
$(...).$results(...)
```

The purpose of this method is to make a method return more than 1 result in a specific repeating sequence. This means that if you set the mock results to be 2 results and you call your method 4 times, the sequence will repeat itself 1 time. MUMBO JUMBO, show me!! Ok Ok, hold your horses.

```javascript
//Mock 3 values for the getSetting method
controller.$("getSetting").$results(true,"cacheEnabled","myapp.model");

//Call getSetting 1
<cfdump var="#controller.getSetting()#">
Results = true

//Call getSetting 2
<cfdump var="#controller.getSetting()#">
Results = "cacheEnabled"

//Call getSetting 3
<cfdump var="#controller.getSetting()#">
Results = "myapp.model"

//Call getSetting 4
<cfdump var="#controller.getSetting()#">
Results = true

//Call getSetting 5
<cfdump var="#controller.getSetting()#">
Results = "cacheEnabled"
```

As you can see, the sequence repeats itself once the call counter increases. Let's say that you have a test where the first call to a user object's `isAuthorized()` method is false but then it has to be true. Then you can do this:

```javascript
mockUser = getMockBox().createMock("model.User");
mockUser.$("isAuthorized").$results(false,true);
```


# $spy()

Spy like us!

MockBox now supports a `$spy( method )` method that allows you to spy on methods with all the call log goodness but without removing all the methods. Every other method remains intact, and the actual spied method remains active. We decorate it to track its calls and return data via the `$callLog()` method.

**Example of CUT:**

```cfscript
void function doSomething(foo){
  // some code here then...
  local.foo = variables.collaborator.callMe(local.foo);
  variables.collaborator.whatever(local.foo);
}
```

**Example Test:**

```cfscript
function test_it(){
  local.mocked = createMock( "com.foo. collaborator" )
    .$spy( "callMe" )
    .$spy( "whatever" );
  variables.CUT.$property( "collaborator", "variables", local.mocked );
  assertEquals( 1, local.mocked.$count( "callMe" ) );
  assertEquals( 1, local.mocked.$count( "whatever" ) );
}
```


# $throws() Method

This method is used to tell MockBox that you want to mock a method with to throw a specific exception. The exception will be thrown instead of the method returning results. This is an alternative to passing the exception in the initial `$()` call. In addition to the fluent API, the `$throws()` method also has the benefit of being able to be tied to specific `$args()` in a mocked object.

To continue with our `getKey()` example:

```javascript
configBean.getKey('DebugMode'); // Exists
configBean.getKey('OutgoingMail'); // Exists
configBean.getKey('IncmingMail'); // Does not exist (see the typo?)
```

We want to test that keys that don't exists throw a `MissingSetting` exception. Let's do that using the `$throws()` method:

```javascript
// get a mock config bean
mockConfig = getMockBox().createEmptyMock( "coldbox.system.beans.ConfigBean" );
// mock the method with args
mockConfig.$( "getKey" ).$args( "debugmode" ).$results( true );
mockConfig.$( "getKey" ).$args( "OutgoingMail" ).$results( "devmail@mail.com" );

// Here's the new $throw call
mockConfig.$( "getKey" ).$args( "IncmingMail" ).$throws( type = "MissingSetting" );

// Then you can call and get the expected results
expect( function(){
    mockConfig.getKey( "IncmingMail" );
} ).toThrow( "MissingSetting" );
```

> **Hint** Remember that the `$throws()` call must be chained to a `$()` or a `$args()` call.


# Verification Methods

The following methods are also mixed in at run-time into mock objects and they will be used to verify behavior and calls from these mock/stub objects. These are great in order to find out how many mocked methods calls have been made and to find out the arguments that where passed to each mocked method call.

| Method Name                                                          | Return Type | Description                                                                                                                       |
| -------------------------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------- |
| $count(\[methodName])                                                | Numeric     | Get the number of times all mocked methods have been called on a mock or pass in a method name and get a the method's call count. |
| $times(count,\[methodName]) or $verifyCallCount(count,\[methodName]) | Numeric     | Assert how many calls have been made to the mock or a specific mock method                                                        |
| $never(\[methodName])                                                | Boolean     | Assert that no interactions have been made to the mock or a specific mock method: Alias to $times(0)                              |
| $atLeast(minNumberOfInvocations,\[methodName])                       | Boolean     | Assert that at least a certain number of calls have been made on the mock or a specific mock method                               |
| $once(\[methodName])                                                 | Boolean     | Assert that only 1 call has been made on the mock or a specific mock method                                                       |
| $atMost(maxNumberOfInvocations, \[methodName])                       | Boolean     | Assert that at most a certain number of calls have been made on the mock or a specific mock method.                               |
| $callLog()                                                           | struct      | Retrieve the method call logger structure of all mocked method calls.                                                             |
| $reset()                                                             | void        | Reset all mock counters and logs on the targeted mock.                                                                            |
| $debug()                                                             | struct      | Retrieve a structure of mocking debugging information about a mock object.                                                        |




---

[Next Page](https://testbox.ortusbooks.com/llms-full.txt/1)

