Skip to content

The Test Context

Matt Barbour edited this page Oct 9, 2015 · 7 revisions

What is the test context

The TestContext is zucchini's "secret-sauce". It is a thread-safe key value store which allows test authors to persist data or objects throughout the lifecycle of a zucchini thread. The primary use for the test context is to store a reference to the java object representing the device under test (in the form of a selenium client for example) for use in the glue code. There is one test context created for each device zucchini attempts to run tests against, and each test context is fully independent from the other contexts unless you explicitly choose to synchronize them using the Barrier Sync feature.

Retrieving java objects from the test context

The test context can be accessed programmatically at any point in the zucchini lifecycle by calling TestContext.getCurrent().get(String nameOfObject)

Under normal circumstances, zucchini glue code should include a retrieval of the java object representing the device under test as the first step in the code. For example:

    @When("^i do something cool$")
    public void loadTheHomePage() {
        // Get the WebDriver object out of the TestContext
        WebDriver webDriverObj = TestContext.getCurrent().get("browser");
        webDriverObj.doSomethingCool();
    }

Storing java objects in the test context

The test context can also be used as a way to persist data across steps and their associated glue code (including between separate classes!)

To write data into the test context, simply call: TestContext.getCurrent().set(String nameOfObject, Object objectReference)

Writing data into the test context is especially helpful for situations where your execution and verification steps can be done in the same step but, for clarity of understanding in the feature file, you need to break them up into separate steps. For example:

    @When("^i do something cool$")
    public void loadTheHomePage() {
        // Get the WebDriver object out of the TestContext
        WebDriver webDriverObj = TestContext.getCurrent().get("browser");
        Boolean result = webDriverObj.doSomethingCool();

        // save off the boolean result from the doSomethingCool method
        TestContext.getCurrent().set("do-something-cool-result", result);
    }
    @Then("^pay me lots of money$")
    public void payMeMoney() {
        // Get the results of the page load from the test context
        Boolean somethingCoolHappened = TestContext.getCurrent().get("do-something-cool-result");
        Assert.assertTrue(somethingCoolHappened,"Something cool didnt happen, better luck next time");
    }

Additionally, application state can be persisted throughout the test context by writing it to the test context. This type of activity should be done with caution as it starts to couple methods in the glue code, which is an anti-pattern in cucumber test authoring.

Next Topic : Test Execution and Reporting