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 } }
Debugger.Launch()in theMainmethod worked well for debugging some tricky cases. However, it does have some drawbacks. (1) It doesn't attach to the same instance of Visual Studio, and (2) it will open up a prompt even if you're not in debug mode. I alleviated this a bit by only launching the debugger when a specific flag is passed as an argument. I got the idea from this question: stackoverflow.com/a/23334014/4555076