Test behaviors

Test behaviors combine action sequences to a logical unit. The behavior defines a set of test actions that can be applied to a Java DSL test case. Following from that you can say that behaviors are reusable test action templates. The maintenance is much more effective when you reuse basic test actions in many test cases.

The behavior is a separate Java DSL class with a single apply method that configures the test actions. Have a look at this first example:

Java DSL

public class FooBehavior extends AbstractTestBehavior {
    public void apply() {
        variable("foo", "test");

        echo("fooBehavior");
    }
}

public class BarBehavior extends AbstractTestBehavior {
    public void apply() {
        variable("bar", "test");

        echo("barBehavior");
    }
}

As you can see the behavior class is able to use the Citrus Java DSL as usual. Each behavior is able to define test variables and actions. In a test case you can apply the behaviors as follows:

Java DSL

@CitrusTest
public void behaviorTest() {
    variable("myTime", "citrus:currentDate()");

    FooBehavior fooBehavior = new FooBehavior();
    applyBehavior(fooBehavior);

    applyBehavior(new BarBehavior());

    applyBehavior(fooBehavior);
}

When dealing with behaviors test actions are defined somewhere outside the test case. How do we handle test variables? A behavior may use different variable names then the test and vice versa. No doubt the behavior will fail as soon as special variables with respective values are not present. Unknown variables cause the behavior and the whole test to fail with errors.

So a good approach would be to harmonize variable usage across behaviors and test cases, so that templates and test cases do use the same variable naming. The behavior automatically knows all variables in the test case. And all test variables created inside the behavior are visible to the test case after applying.

Important When a behavior changes variables this will automatically affect the variables in the whole test. So if you change a variable's value inside a behavior and the variable is defined inside the test case the changes will affect the variable in a global test context. This means we have to be careful when executing a behavior several times in a test, especially in combination with parallel containers (see containers-parallel).

Behavior types

The test case in Java is able to follow either designer or runner strategies. This means we also have two different behavior types for designer and runner respectively. The behaviors are located in separate packages

  • com.consol.citrus.dsl.design.AbstractTestBehavior
  • com.consol.citrus.dsl.runner.AbstractTestBehavior

Decide which base behavior you want to extend from according to your test case nature.