我的基类中有以下代码,用于所有 Allure 支持的测试:
[AllureNUnit]
internal abstract class PageTestBase : Microsoft.Playwright.NUnit.PageTest
{
protected async Task Step(string name, Func<Task> action)
{
try
{
await AllureApi.Step(name, action);
}
catch (Exception)
{
//save screenshot in case something goes wrong (mandatory)
await Page.ScreenshotAsync(new() { Path = "failure.png" });
//TODO: set result to failed
}
//TODO: depending on settings user can opt to save screenshots after every step
await Page.ScreenshotAsync(new() { Path = "AfterEachStep.png" });
}
}
我希望能够创建一个步骤抽象,允许在步骤完成后做出反应(即失败后截取屏幕截图,并可选择在每个步骤后截取屏幕截图)。如何在 Allure.NUnit 中实现这一点?
对我有用的解决方案是从 Allure 复制一些代码并对其进行自定义,以便创建适当的状态机:
public Task UiStep(string name, Func<Task> action) =>
ExecuteStepAsync(name, async () =>
{
await action();
return Task.FromResult<object?>(null);
});
/// <summary>
/// Executes the asynchronous function and reports the result as a new step
/// of the current fixture, test or step. Requires one of these contexts to
/// be active.
/// </summary>
/// <param name="name">The name of the step.</param>
/// <param name="function">The asynchronous function to run.</param>
/// <returns>The original value returned by the function.</returns>
public Task<T> UiStep<T>(string name, Func<Task<T>> function) => ExecuteStepAsync(name, function);
private async Task<T> ExecuteStepAsync<T>(string name, Func<Task<T>> action)
{
T result;
Exception? error = null;
ExtendedApi.StartStep(name);
try
{
result = await action();
}
catch (Exception e)
{
error = e;
await SaveScreenshot(Page, _reportingSettings.FailureScreenshots, name);
throw;
}
finally
{
ExtendedApi.ResolveStep(error);
await SaveScreenshot(Page, _reportingSettings.EveryStepScreenshots, name);
}
return result;
}