Add Unit Tests
To avoid regression, we recommend adding unit tests for all your tasks.
There are two main ways to unit-test your tasks. In both cases, your tests must be annotated with @KestraTest
to start the needed Kestra components properly.
Unit test a RunnableTask
This is the most common way to test a RunnableTask
. You create your RunnableTask
, test its run()
method, and assert on its output or exception.
Example
@KestraTestclass ExampleTest { @Inject private RunContextFactory runContextFactory;
@Test void run() throws Exception { RunContext runContext = runContextFactory.of(Map.of("variable", "John Doe"));
Example task = Example.builder() .format("Hello {{ variable }}") .build();
Example.Output runOutput = task.run(runContext);
assertThat(runOutput.getChild().getValue(), is(StringUtils.reverse("Hello John Doe"))); }}
This is done the same as any Java unit tests. Feel free to use any dependencies, test methods, and start docker containers as you need. Kestra tests are Micronaut tests so you can inject any bean in them.
Unit test with a full flow
If you want to add some unit tests with a full flow (which can be necessary in some rare cases, for example, for a FlowableTask
), you will use the @ExecuteFlow
annotation.
Example
@KestraTest(startRunner = true) // This annotation starts an embedded Kestra for testsclass ExampleRunnerTest { @Test @ExecuteFlow("flows/example.yaml") void flow(Execution execution) throws TimeoutException, QueueException { assertThat(execution.getTaskRunList(), hasSize(3)); assertThat(((Map<String, Object>)execution.getTaskRunList().get(2).getOutputs().get("child")).get("value"), is("task-id")); }}
@KestraTest(startRunner = true)
will start Kestra with an in-memory backend.@ExecuteFlow("flows/example.yaml")
will start the flow from thesrc/test/resources/flows/example.yaml
file and execute it.- The created execution is then available for test method parameter injection so that you can make assertions on it.
To make it work, you need to have an application.yml
file with this minimum configuration:
kestra: repository: type: memory queue: type: memory storage: type: local local: base-path: /tmp/unittest
And these dependencies on your build.gradle
:
testAnnotationProcessor group: "io.kestra", name: "processor", version: kestraVersiontestImplementation group: "io.kestra", name: "core", version: kestraVersiontestImplementation group: "io.kestra", name: "tests", version: kestraVersiontestImplementation group: "io.kestra", name: "repository-memory", version: kestraVersiontestImplementation group: "io.kestra", name: "runner-memory", version: kestraVersiontestImplementation group: "io.kestra", name: "storage-local", version: kestraVersion
This will enable the in memory runner and will run your flow without any other dependencies (e.g., kafka). If you created it from our plugin template, those are usually already included in your project.