Expotr
Expotr

Reputation: 49

How to ingration test Console App attached to Visual Studio debugger

I'm making a Console App and I want to create the kind of integration/component tests I'm used to for ASP.NET Core applications using WebApplicationFactory<>.

However, I haven't been able to find a way to test the Console App in an attached way that ensures I can set breakpoints in the Console App during debugging tests.

I have tried to hack something together using the following answer, but I didn't achieve breakpoints. By the time it's trying to attach, the process has already terminated.

https://stackoverflow.com/a/72075450

Is there a better way I'm overlooking?

Simplified version of my current code:

internal class Program
{
    static async Task Main(string[] args)
    {
        var host = Host.CreateDefaultBuilder(args)
            .UseConsoleLifetime()
            .ConfigureServices((_, services) => services.AddHostedService<CustomHostedService>())
            .Build();

        await host.RunAsync();
    }
}
internal class CustomHostedService : IHostedService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;

    public CustomHostedService(IHostApplicationLifetime hostApplicationLifetime)
    {
        _hostApplicationLifetime = hostApplicationLifetime;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        // Actual code for the application

        _hostApplicationLifetime.StopApplication();
    }

    public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
internal class IntegrationTests
{
    [Fact]
    public void Executable()
    {
        Process.Start("{assemblyName}.exe {arguments}")
        
        // Asserts
    }

    [Fact]
    public void DotnetRun()
    {
        Process.Start("dotnet", "run --project {project_path} {arguments}");

        // Asserts
    }
}

Upvotes: 1

Views: 403

Answers (1)

Jeremy Thompson
Jeremy Thompson

Reputation: 65554

If it's a console app run it with AutoHotKey, or SikuliX for wimforms or another system as a testing framework.

Selenium is popular for testing websites but console and winform are completely different they aren't designed for the WebApplicationFactory<> pattern.

You maybe able to do it though there's a reason you're unable to find examples of others going down this mismatching technology path as it's unorthodox and unsupported.

I'd try out AHK and SikuliX, both are free and reconsider attaching a debugger to the process - that's typically useful for troubleshooting systems with problems that can't be reproduced. Where as you're just running a console app with a bunch of logic code paths you can easily verify by reading the StdOut to various sequences of inputs.

Upvotes: 1

Related Questions