TestExtensionsAspire- part 2- execution

Now the code mans to create commands about running dotnet <test or run> in the current folder of the csproj test project.

Things that needed to be solved:

1.    Test Project as NuGet Package
The main project (.csproj)  , that will be referenced as a NuGet dependency, it’s not an Aspire project, so it doesn’t natively support Aspire’s resource model or command system.
Solution:

    <ProjectReference Include="..\TestExtensionsAspire\TestExtensionsAspire.csproj" IsAspireProjectResource="false" />

2.    Environment Variable Propagation
Tests often require environment variables (connection strings, URLs, secrets) that are configured in Aspire. These must be transferred to the test process when running commands.
Solution

var b= testProject.Resource.TryGetEnvironmentVariables(out var envCallback);
envCallback ??= [];
Dictionary<string, object> envDict = new();
EnvironmentCallbackContext environmentCallbackContext = new(builder.ExecutionContext, envDict);
foreach (var env in envCallback)
{
    await env.Callback(environmentCallbackContext);

}
var envs = environmentCallbackContext.EnvironmentVariables;
                foreach (var env in envs)
{
    if (env.Value is EndpointReference ref1)
    {
        exportStartInfo.Environment.Add(env.Key, ref1.Url);
        continue;
    }
    exportStartInfo.Environment.Add(env.Key, env.Value?.ToString());
}

3.    Command Output Integration
The output of the test command (dotnet test or dotnet run) should be visible in the Aspire Console for the test project, ensuring full traceability and debugging support.

Solution:

var loggerService = ctx.ServiceProvider.GetService(typeof(ResourceLoggerService)) as ResourceLoggerService;
var logger = loggerService?.GetLogger(testProject.Resource);

Now you can enjoy https://www.nuget.org/packages/testextensionsaspire#readme-body-tab

builder.AddTestProject<Projects.TestExtensions_Tests>("SampleTests",
        "run  --filter-trait 'Category=UnitTest'",
        "run --filter-trait 'Category=Logic'")
    .WithReference(apiService)
    .WithReference(web)
    .WithEnvironment("url", "asd")

Posted

in

, , ,

by

Tags: