Test actions give automation code a uniform way to perform an action and apply shared functionality, such as logging, timing, and failure handling. This keeps step definitions focused on testing decisions and makes actions easier to reuse and reorganize. section 15.0 section 15.4
A practical implementation separates the shared execution behavior from the action itself:
- A base class wraps execution with logging, elapsed-time reporting, and exception logging before rethrowing failures. section 15.4
- Concrete actions provide the work to perform. For simple actions, a lambda-based action avoids creating a separate derived class; more complicated actions can use dedicated classes. section 15.4
Listing 15.13 Base class for test actions
*** Support/TestAction.cs ***
public abstract class TestAction<TResult>(string actionName)
{
public string TestActionName => testActionName;
protected abstract Task<TResult> DoExecute(); #A
public async Task<TResult> Execute()
{
try
{
Console.WriteLine($"Executing {TestActionName}...");
var stopwatch = Stopwatch.StartNew();
var result = await DoExecute(); #B
Console.WriteLine(
$"{TestActionName} executed successfully in {stopwatch.Elapsed}.");
return result;
}
catch (Exception ex)
{
Console.WriteLine($"{TestActionName} failed: {ex.Message}");
throw;
}
}
}See how a base action wraps the delegated work with logging, timing, and exception handling. section 15.4
