### Generate TestBox Testing Harness Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Use the TestBox CLI to quickly set up a testing harness in your project. This command adds a new `/tests` folder with example tests, resources, and runner files to get you started. ```bash testbox generate harness ``` -------------------------------- ### Travis CI Install Step for CommandBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/travis.md This snippet focuses on the `install` section of the `.travis.yml` file. It details the commands necessary to update the system's package list, install CommandBox via `apt-get`, and then use CommandBox to install project dependencies (`box install`) and start the CFML server (`box server start`) before test execution. ```yaml install: - sudo apt-get update && sudo apt-get --assume-yes install commandbox - box install - box server start ``` -------------------------------- ### Implement TestBox Setup and Teardown for Resource Management Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/setup-and-teardown.md This example demonstrates how to use TestBox's `setup` and `teardown` methods within an xUnit test suite to manage application resources like an IoC injector. The `setup` method initializes resources before each test, and `teardown` cleans them up afterwards, ensuring a clean state for subsequent tests. It also includes example test cases using assertion methods. ```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();; }); } } ``` -------------------------------- ### GitHub Actions Setup Steps: Checkout, Java, CommandBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/github-actions.md This YAML configuration details the initial setup steps for a GitHub Actions job. It includes checking out the repository code, installing Java Development Kit version 11, and setting up CommandBox using a dedicated action. ```YAML - 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 CommandBox uses: Ortus-Solutions/setup-commandbox@main ``` -------------------------------- ### Travis CI Configuration for TestBox with CommandBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/travis.md This comprehensive `.travis.yml` file outlines the full setup for running TestBox tests on Travis CI. It specifies the Java language, required sudo privileges, and Ubuntu Trusty distribution. The `before_install` step adds CommandBox repository keys and installs CommandBox. The `install` step updates apt, installs CommandBox, and then uses `box install` and `box server start` to prepare the CFML environment. Finally, the `script` step executes TestBox tests. ```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 ``` -------------------------------- ### TestBox xUnit Style Testing Examples Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/README.md This snippet illustrates how to implement xUnit style tests in TestBox for both BoxLang and CFML. It demonstrates defining a setup function, naming conventions for test methods (e.g., starting with 'test'), and using annotations ('@test' or 'test' keyword) for test identification, along with expectations and assertions. ```BoxLang /** * 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 ) } } ``` ```CFML /** * 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 ) } } ``` -------------------------------- ### xUnit Style Test Example (CFML) Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/overview.md Illustrates the traditional xUnit (Test Driven Development) approach in TestBox. It defines a test class with `setup` and test methods, showcasing both `expect` and `$assert` for assertions. ```cfscript @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 ) } } ``` -------------------------------- ### Complete GitHub Actions Workflow for TestBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/github-actions.md This comprehensive YAML example provides a full GitHub Actions workflow file (`tests.yml`) for integrating TestBox. It combines all necessary steps: defining triggers, checking out code, setting up Java and CommandBox, installing dependencies, starting a CFML server, and running TestBox tests. ```YAML # .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 CommandBox uses: Ortus-Solutions/setup-commandbox@main - 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 ``` -------------------------------- ### xUnit Style Testing with TestBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/overview.md Illustrates xUnit style testing in TestBox, a more traditional unit testing approach. Examples show the use of 'setup' for test fixture initialization, and different ways to define test methods (e.g., 'test' prefix, '@test' annotation in BoxLang, or 'test' keyword in CFML) using 'expect' and '$assert' for assertions. ```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 ) } } ``` ```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 ) } } ``` -------------------------------- ### Nest TestBox describe blocks with setup and teardown Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-bdd-primer/suite-groups/README.md This example illustrates how to nest `describe()` blocks to create a hierarchical test structure in TestBox. It also demonstrates the use of `beforeEach()` and `afterEach()` functions to perform setup and teardown operations before and after each spec within their respective scopes, showing how variables and application contexts can be managed across nested suites. ```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 ); }); }); ``` -------------------------------- ### xUnit Lifecycle Methods (CFML) Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/overview.md Demonstrates the `setup`, `tearDown`, `beforeTests`, and `afterTests` lifecycle callbacks used in TestBox's xUnit style for managing test environment setup and teardown. ```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() } ``` -------------------------------- ### TestBox Test Case with @beforeEach Annotation and Integration Test Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/life-cycle-methods.md This ColdFusion component, `PostsTest.cfc`, extends `DBTestCase` and illustrates the use of the `@beforeEach` annotation to ensure the `setup()` method is called before each test spec. It includes an integration test example that inserts data, executes a ColdBox event, and asserts the rendered content, demonstrating how to test web application flows within TestBox. ```CFML 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" ); }); }); }); } } ``` -------------------------------- ### Install TestBox CLI Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Install the TestBox Command Line Interface (CLI) to enable `testbox` commands for generating tests, harnesses, and running executions directly from the terminal. ```bash install testbox-cli ``` -------------------------------- ### Display TestBox CLI Help Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Show available commands and options for the TestBox CLI, providing guidance on how to use its various functionalities. ```bash testbox help ``` -------------------------------- ### Install and Register FusionReactor with CommandBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction/running-code-coverage.md This snippet provides CommandBox commands to install the `commandbox-fusionreactor` module and register your FusionReactor license. Once executed, FusionReactor will be automatically configured for all subsequent servers started via CommandBox, enabling its use for TestBox code coverage. ```bash install commandbox-fusionreactor fr register ``` -------------------------------- ### Install bx-web-support Module Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/readme/release-history/whats-new-with-6.0.0.md Commands to install the `bx-web-support` module, which adds web support (BIFS, components, mock HTTP server) to the BoxLang CLI for headless web server testing. ```Bash // CommandBox install bx-web-support // BoxLang OS Binary install-bx-module bx-web-support ``` -------------------------------- ### Install TestBox with CommandBox CLI Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Install TestBox as a development dependency using CommandBox CLI. This snippet shows how to create a new project and then install either the latest stable version or the bleeding-edge version of TestBox. ```bash // Create a new project mkdir myProject --cd // latest stable version box install testbox --saveDev // latest bleeding edge box install testbox@be --saveDev ``` -------------------------------- ### TestBox Class Execution Methods and Examples Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/README.md Demonstrates the main execution methods of the `TestBox` class for running tests and retrieving results, along with examples for remote execution via URL and CLI. ```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 ``` -------------------------------- ### Start CFML Server and Run TestBox Tests Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/github-actions.md This YAML snippet shows how to start a CFML server (Lucee 5.3) using CommandBox and then execute TestBox tests. It uses the `box server start` command to launch the server and `box testbox run` to initiate the test suite. ```YAML - name: Start server run: box server start cfengine=lucee@5.3 --noSaveSettings - name: Run TestBox Tests run: box testbox run ``` -------------------------------- ### Example TestBox xUnit Test Bundle Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/README.md This CFScript code defines a TestBox test component, `BaseSpec`, demonstrating lifecycle methods (`beforeTests`, `afterTests`, `setup`, `teardown`) and various assertion functions (`testFloatingPointNumberAddition`, `testIncludes`, `testIncludesWithCase`, `testNotIncludes`, `testIsEmpty`, `testIsNotEmpty`, `testSkipped`) for unit testing. ```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\n\t\t\t1 | luis" ) ); } function testSkipped() skip{ $assert.fail( "This Test should fail" ); } ``` -------------------------------- ### Example TestBox configuration in box.json Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/commandbox-runner.md Illustrates the structure and available options within the `testbox` entry of a `box.json` file, allowing pre-configuration of test bundles, directories, exclusions, labels, and runner settings. ```json "testbox":{ "bundles":"", "directory":"tests.specs", "excludes":"", "labels":"", "options":{}, "recurse":true, "reporter":"", "runner":[ { "default":"" } ], "testBundles":"", "testSpecs":"", "testSuites":"", "verbose":true, "watchDelay":500, "watchPaths":"**.cfc" } ``` -------------------------------- ### Install TestBox NodeJS Runner globally Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/nodejs-runner.md This command installs the `testbox-runner` package globally using npm, making the `testbox-runner` command available from any directory in your system. ```bash npm install -g testbox-runner ``` -------------------------------- ### Applying Labels to TestBox Suite and Methods Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/test-and-suite-labels.md This example demonstrates how to apply labels to a TestBox component (suite) globally and to individual test methods. It includes setup and teardown functions, along with various assertion tests, showcasing how the 'labels' attribute can be used for selective test execution. ```ColdFusion 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" ); } } ``` -------------------------------- ### Set Project Language via CLI Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Use the `package set language` command to explicitly define the project's preferred language for code generation and tooling detection. This example shows how to set it for BoxLang or CFML. ```bash # For BoxLang Generation package set language="boxlang" # For CFML package set language="cfml" ``` -------------------------------- ### Display TestBox CLI Run Command Help Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Show available options and parameters for the `testbox run` command, which is used for executing tests from the CommandBox CLI. ```bash testbox run --help ``` -------------------------------- ### TestBox BoxLang CLI Runner Examples (Windows) Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/boxlang-cli-runner.md Examples demonstrating how to execute TestBox tests using the BoxLang CLI runner on Windows systems. This includes running all tests, a specific test bundle, or tests located within a specified directory. ```bash ./testbox/run.bat ./testbox/run.bat my.bundle ./testbox/run.bat --directory=tests.specs ./testbox/run.bat --bundles=my.bundle ``` -------------------------------- ### TestBox BoxLang CLI Runner Examples (Mac/Linux) Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/boxlang-cli-runner.md Examples demonstrating how to execute TestBox tests using the BoxLang CLI runner on Mac and Linux systems. This includes running all tests, a specific test bundle, or tests located within a specified directory. ```bash ./testbox/run ./testbox/run my.bundle ./testbox/run --directory=tests.specs ./testbox/run --bundles=my.bundle ``` -------------------------------- ### MockBox: Prepare Existing Object for Mocking Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/creating-a-mock-object.md Example demonstrating how to use `mockBox.prepareMock()` to add mocking capabilities to an already instantiated object, `myService`. This allows for targeted mocking of specific methods or properties. ```CFML myService = createObject("component","model.services.MyCoolService").init(); // prepare it for mocking mockBox.prepareMock( myService ); ``` -------------------------------- ### MockBox: Create Mock Object Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/creating-a-mock-object.md Example demonstrating how to use `mockbox.createMock()` to create a mock object for a class named 'model.myClass'. This snippet shows a basic instantiation of a mock. ```CFML collaborator = mockbox.createMock("model.myClass"); ``` -------------------------------- ### Define Test Bundle Component with Lifecycle Hooks Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/bundles-group-your-tests.md Shows a TestBox test bundle component, labeled as JavaScript in the source, extending `testbox.system.BaseSpec`. This example includes the `beforeTests` and `afterTests` lifecycle methods, which are executed before and after all tests within the bundle, respectively, for setup and teardown operations. ```javascript component displayName="My test suite" extends="testbox.system.BaseSpec"{ // executes before all tests function beforeTests(){} // executes after all tests function afterTests(){} } ``` -------------------------------- ### Install Project Dependencies with CommandBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/github-actions.md This step demonstrates how to install project dependencies using CommandBox within a GitHub Actions workflow. The `box install` command is executed to resolve and download required packages. ```YAML - name: Install dependencies run: box install ``` -------------------------------- ### Start TestBox watcher with server Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/commandbox-runner.md Outlines the necessary steps to activate the TestBox code watcher, including setting the runner URL, ensuring the server is running, and initiating the watch process. ```bash package set testbox.runner=http://localhost:8080/tests/runner.cfm server start testbox watch ``` -------------------------------- ### TestBox CLI Configuration in box.json Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/running-tests.md Example `box.json` configuration for TestBox CLI, specifying the runner URL, file watchers, and watch delay for automated test execution. ```json "testbox":{ "runner":"http://localhost:49616/tests/runner.cfm", "watchers":[ "system/**.cfc", "tests/**.cfc" ], "watchDelay":"250" } ``` -------------------------------- ### Enable Asynchronous Testing in TestBox Component Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/asynchronous-testing.md This TestBox component demonstrates how to enable asynchronous execution for all specs within a test bundle using the `asyncAll=true` annotation. It includes `setup` and `teardown` functions for application context management, and example tests for `throws` and `notThrows` assertions, along with a private helper function. ```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 ); } } ``` -------------------------------- ### TestBox Method Spying for Unit Testing Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/some-examples.md This TestBox example illustrates how to effectively unit test the `userValidator` function using method spies. The `beforeAll` setup prepares mock objects, and the `run` block uses TestBox's `$()` and `$results()` methods to mock the behavior of internal dependencies like `isAuthorized`, `getUserSession`, `isSSOCookieValid`, and `authorizeUser`. This allows for comprehensive testing of `userValidator`'s different execution paths without invoking the actual logic of its helper methods. ```javascript function beforeAll(){ //target object security = prepareMock( createObject("component","model.Security") ); //create a mock user object mockUser = createEmptyMock("model.User"); } function run(){ describe( "A user", function(){ it( "can be authenticated", function(){ //mock user authorizations according to case calls mockUser.$("isAuthorized").$results(true,false,false); security.$("getUserSession", mockUser); //case 1: authorized user expect(security.userValidator()).toBeTrue(); //case 2: unauthorized user with invalid cookie security.$("isSSOCookieValid",false); expect( security.userValidator() ).toBeFalse(); //case 3: unauthorized user with valid cookie security.$("isSSOCookieValid",true); //mock the authorizeUser void call security.$("authorizeUser"); expect( security.userValidator() ).toBeTrue(); }); }); } ``` -------------------------------- ### Install BoxLang Web Support Module for CLI Testing Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/boxlang-cli-runner.md Command to install the 'bx-web-support' module into the BoxLang CLI runtime, enabling web application testing directly from the command line without a dedicated web server. ```bash install-bx-module bx-web-support ``` -------------------------------- ### Install TestBox Module from ForgeBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/modules.md Command to install a TestBox module from ForgeBox using its ID, specifying the installation directory. ```bash install id=module directory=testbox/system/modules ``` -------------------------------- ### TestBox BoxLang Spec Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/readme/release-history/whats-new-with-6.0.0.md A sample TestBox specification written in BoxLang, demonstrating basic test structure, describing test suites, and asserting expectations. ```BoxLang 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 } } ``` -------------------------------- ### Mocking DSL Query String Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mocking-data.md Shows an example of using the cbMockData Mocking DSL via a URL query string. This demonstrates how to specify the number of items and an author's name for data generation. ```JavaScript http://localhost:3000/?$num=3&author=name ``` -------------------------------- ### MockBox: Create Empty Mock Object Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/creating-a-mock-object.md Example demonstrating how to use `mockbox.createEmptyMock()` to create an empty mock object for a class named 'model.User'. This is useful when you want to define all mock behavior from scratch. ```CFML user = mockbox.createEmptyMock("model.User"); ``` -------------------------------- ### Get help for TestBox watcher Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/commandbox-runner.md Displays the command to access help and available options for the `testbox watch` command, which provides continuous test execution on file changes. ```bash testbox watch help ``` -------------------------------- ### Accessing the TestBox Web Runner Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/test-runner.md Example URL to access the default TestBox web runner, which executes all tests by convention found in the 'tests/specs' folder. ```HTTP http://localhost/tests/runner.cfm ``` -------------------------------- ### TestBox Bundle `beforeAll` and `afterAll` Life-Cycle Methods Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-bdd-primer/bundles-group-your-tests.md These methods define the global setup and teardown logic for a TestBox bundle. `beforeAll()` executes once before all test suites, and `afterAll()` executes once after all test suites, ideal for resource initialization or cleanup. ```cfscript // executes before all suites function beforeAll(){} // executes after all suites function afterAll(){} ``` -------------------------------- ### ModuleConfig.cfc Mandatory Callbacks Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/modules.md Example `cfscript` code for the `ModuleConfig.cfc` file, demonstrating the three mandatory callback functions: `configure`, `onLoad`, and `onUnload`. ```cfscript component{ function configure(){ } function onLoad(){ } function onUnload(){ } } ``` -------------------------------- ### BDD Style Test Example (CFML) Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/overview.md Demonstrates how to write tests using the Behavior Driven Development (BDD) style in TestBox. It shows the use of `describe`, `beforeEach`, `it`, `expect`, and `$assert` for defining test suites and assertions. ```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 ) } ) } ) ``` -------------------------------- ### TestBox Mocking: Advanced $() Method Examples Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/mocking-methods/usd-method.md Provides various examples of using the `$` method for advanced mocking scenarios, including setting specific return values, defining return sequences, mocking method calls to return objects, configuring methods to throw exceptions, and enabling call logging for inspection. ```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 ``` -------------------------------- ### Assertions and Expectations Usage (CFML) Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/overview.md Provides examples of using both the traditional `assert` library and the fluent `expect` library for making assertions in TestBox tests. ```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" ); ``` -------------------------------- ### Generate TestBox BDD or Unit Tests Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/installing-testbox/README.md Use the TestBox CLI to create new test files, supporting both Behavior-Driven Development (BDD) and Unit testing styles. The CLI automatically detects if you are using BoxLang or a CFML engine. ```bash testbox create bdd --help testbox create unit --help ``` -------------------------------- ### BDD Style Testing with TestBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/overview.md Demonstrates Behavior-Driven Development (BDD) style testing using TestBox. This approach focuses on describing behavior from the perspective of the user. Examples show the use of 'describe', 'beforeEach', 'it', 'expect', and 'test' with '$assert' for assertions. ```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 ) } ) } ) } } ``` ```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 ) } ); } ); } } ``` -------------------------------- ### Execute TestBox Runner Script via Web Server Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/bundle-s-runner.md Example URL for running a TestBox script (BoxLang .bxs or CFML .cfm) by accessing it through a web server, assuming it's placed in a web-accessible directory like /tests/. ```text http://localhost/tests/run.bxs ``` -------------------------------- ### Create and start a ColdBox sample application with CommandBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction/running-code-coverage.md These CommandBox commands facilitate the creation of a ColdBox sample application and the immediate startup of a local server. This provides a ready-to-use test suite environment, demonstrating TestBox's mechanics even though ColdBox is not a strict requirement. ```bash coldbox create app server start ``` -------------------------------- ### TestBox Lifecycle Hooks Execution Order Example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-bdd-primer/life-cycle-methods.md Demonstrates the sequence of execution for beforeEach, aroundEach, afterEach, and it within a single TestBox describe block. The comments within the code indicate the relative firing order of each hook. ```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 } ); } ); ``` -------------------------------- ### Example of Code Under Test for $spy() Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/mocking-methods/usdspy.md Illustrates a simple function `doSomething` that interacts with a collaborator, which can then be spied upon using MockBox's `$spy()` method. This code represents the component being tested. ```cfscript void function doSomething(foo){ // some code here then... local.foo = variables.collaborator.callMe(local.foo); variables.collaborator.whatever(local.foo); } ``` -------------------------------- ### TestBox NodeJS Runner configuration file example Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/nodejs-runner.md This JSON configuration file, named `.testbox-runnerrc`, specifies the URL of the TestBox runner, the directory containing test specifications, and whether to recursively search for tests within subdirectories. ```json { "runner": "http://localhost/testbox/system/runners/HTMLRunner.cfm", "directory": "/tests/specs", "recurse": true } ``` -------------------------------- ### TestBox Test Method Discovery Conventions and Annotations Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-xunit-primer/test-methods.md Illustrates how TestBox discovers test methods using inline annotations, comment annotations, and naming conventions (methods starting or ending with 'test'). ```javascript // Via inline annotation function shouldBeAwesome() test{} /** * Via comment annotation * @test */ function shouldBeAwesome(){} // via conventions function testShouldDoThis(){} function shouldDoThisTest(){} ``` -------------------------------- ### Basic TestBox run commands Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/running-tests/commandbox-runner.md Demonstrates fundamental `testbox run` commands, including accessing help, specifying test directories, defining output formats (JSON, JUnit, HTML), and connecting to a remote runner URL. ```bash testbox run help testbox run directory="tests.specs" outputFormats="json,junit,html" testbox run runner="http://myremoteapp.com/tests/runner.cfm" ``` -------------------------------- ### TestBox Expectations and Matchers Examples Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/testbox-bdd-primer/expectations.md This JavaScript code demonstrates the core functionality of TestBox expectations. It shows how to use `expect()` with `toBe` for equality checks (both positive and negative cases with `notToBe`), and how to use `expectAll()` with `toSatisfy` for validating conditions across elements in a collection. ```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; }); }); }); } ``` -------------------------------- ### Configure box.json for TestBox Runner Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/github-actions.md Example `box.json` configuration demonstrating the `testbox.runner` property, which specifies the URL for the TestBox test runner. This allows `box testbox run` to execute tests correctly by connecting to the server and knowing which tests to execute. ```JSON { "name" : "Package Name", "slug" : "", "version" : "1.0.0+buildID", "author" : "Luis Majano ", "location" : "URL,Git/svn endpoint,etc", "testbox" :{ "runner" : [ { "default": "http://localhost:8080/tests/runner.cfm" } ] } } ``` -------------------------------- ### TestBox: User Service Test Case with MockBox Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/mocking/mockbox/creating-a-mock-object.md A comprehensive TestBox test case demonstrating how to set up and test a `UserService` by mocking its dependencies (`sessionstorage`, `transfer`, `userDAO`) using `createMock()` and `createEmptyMock()`. It includes a `beforeAll` method for test setup and an `it` block for testing data retrieval with `querySim` and method mocking. ```CFML 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\n 1|Luis Majano\n 2|Alexia Majano"); // mock the DAO call with this mocked query as its return mockDAO.$("getData", mockQuery); data = userService.getData(); expect( data ).toBe( mockQuery ); }); }); } } ``` -------------------------------- ### Generate TestBox Test Bundles via CLI Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/getting-started/test-bundles.md Illustrates command-line interface (CLI) commands for creating new BDD or xUnit style test bundles in TestBox. Examples include using `--help` for options and specifying bundle names and output directories. ```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/" ``` -------------------------------- ### Gitlab CI Pipeline Configuration for TestBox Integration Source: https://github.com/ortus-docs/testbox-docs/blob/v6.x/digging-deeper/introduction-1/gitlab.md This YAML configuration defines a Gitlab CI pipeline using the `ortussolutions/commandbox:alpine` Docker image. It sets up `build`, `test`, and `deploy` stages, including a `run_tests` job that installs dependencies, starts a CFML server, and executes TestBox tests. The `run_tests` job is configured to run only on the `development` branch. ```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 ```