Fluent Commerce Logo
Docs

Rule Context Generator

Essential knowledgeCore knowledge to understand Fluent Commerce

Intended Audience:

Technical User

Author:

Kirill Gaiduk

Changed on:

5 Sept 2025

Overview

The `RuleContextGenerator` is the underlying class that the `RuleExecutor` and `WorkflowExecutor` use to construct a mock `Context` for your tests. While you will most often interact with it through the executors, you can also use it directly to manually create a `Context` object.This is particularly useful when you are unit testing a helper or utility class that requires a `Context` object as a parameter, but you don't need to execute a full rule.

Key points

  • Core Context Builder: `RuleContextGenerator` is the fundamental builder class that the `RuleExecutor` and `WorkflowExecutor` use to create the mock `Context` for your tests.
  • Direct Instantiation: You can use it directly (`RuleContextGenerator.of(...)`) when you need a `Context` object for testing a helper class or utility method, but don't need to execute a full rule.
  • Action Tracking: It automatically captures and tracks all actions (events, mutations, logs) performed during execution, providing methods like `getActionsOfType()` and `getLastActionOfType()` for verification.
  • Foundation of Testing: It is the foundational component of the test utilities, providing the mock environment that makes isolated unit and integration testing possible.

Core Methods

`of` (Event, MockApiClient)
To create a `Context` manually with a specific event and mock API client, use the static factory `RuleContextGenerator.of(event, mockApiClient)`.
`of` (MockApiClient)
To create a `Context` manually with a specific mock API client, use the static factory `RuleContextGenerator.of( mockApiClient)`.
`forRule`
To configure the context for a specific rule instance, use the `forRule()` method. This sets up the rule properties and configuration.
`mockApiClient`
To replace the executor's default API mock with your own, use the `RuleContextGenerator.mockApiClient` method. This allows you to reuse the same mocks across different tests.
`getActions`
To retrieve the actions produced during execution, use the `RuleContextGenerator.getActions` method:
`getActionsOfType`
To retrieve the actions produced during execution filtered by a specific type, use the `RuleContextGenerator.getActionsOfType` method:
`getFirstActionOfType`
To retrieve the first action of a given type that was produced during execution, use the `RuleContextGenerator.getFirstActionOfType` method:
`getLastActionOfType`
To retrieve the last action of a given type that was produced during execution, use the `RuleContextGenerator.getLastActionOfType` method:

Complete Example

Here's a complete example showing how to use `RuleContextGenerator` directly: