How to use ConsoleRunner class of Xunit.Runner.SystemConsole package

Best Xunit code snippet using Xunit.Runner.SystemConsole.ConsoleRunner

ConsoleRunner.cs

Source:ConsoleRunner.cs Github

copy

Full Screen

...16/// <summary>17/// This class is the entry point for the in-process console-based runner used for18/// xUnit.net v3 test projects.19/// </summary>20public class ConsoleRunner21{22	readonly string[] args;23	volatile bool cancel;24	readonly object consoleLock;25	bool executed = false;26	bool failed;27	IRunnerLogger? logger;28	IReadOnlyList<IRunnerReporter>? runnerReporters;29	readonly Assembly testAssembly;30	readonly TestExecutionSummaries testExecutionSummaries = new();31	/// <summary>32	/// Initializes a new instance of the <see cref="ConsoleRunner"/> class.33	/// </summary>34	/// <param name="args">The arguments passed to the application; typically pulled from the Main method.</param>35	/// <param name="testAssembly">The (optional) assembly to test; defaults to <see cref="Assembly.GetEntryAssembly"/>.</param>36	/// <param name="runnerReporters">The (optional) list of runner reporters.</param>37	/// <param name="consoleLock">The (optional) lock used around all console output to ensure there are no write collisions.</param>38	public ConsoleRunner(39		string[] args,40		Assembly? testAssembly = null,41		IEnumerable<IRunnerReporter>? runnerReporters = null,42		object? consoleLock = null)43	{44		this.args = Guard.ArgumentNotNull(args);45		this.testAssembly = Guard.ArgumentNotNull("testAssembly was null, and Assembly.GetEntryAssembly() returned null; you should pass a non-null value for testAssembly", testAssembly ?? Assembly.GetEntryAssembly(), nameof(testAssembly));46		this.consoleLock = consoleLock ?? new object();47		this.runnerReporters = runnerReporters.CastOrToReadOnlyList();48	}49	/// <summary>50	/// The entry point to begin running tests.51	/// </summary>52	/// <returns>The return value intended to be returned by the Main method.</returns>53	public async ValueTask<int> EntryPoint()54	{55		if (executed)56			throw new InvalidOperationException("The EntryPoint method can only be called once.");57		executed = true;58		var globalInternalDiagnosticMessages = false;59		var noColor = false;60		try61		{62			var commandLine = new CommandLine(testAssembly, args, runnerReporters);63			if (commandLine.HelpRequested)64			{65				PrintHeader();66				Console.WriteLine("Copyright (C) .NET Foundation.");67				Console.WriteLine();68				Console.WriteLine($"usage: [path/to/configFile.json] [options] [filters] [reporter] [resultFormat filename [...]]");69				commandLine.PrintUsage();70				return 2;71			}72			var project = commandLine.Parse();73			AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;74			Console.CancelKeyPress += (sender, e) =>75			{76				if (!cancel)77				{78					Console.WriteLine("Canceling... (Press Ctrl+C again to terminate)");79					cancel = true;80					e.Cancel = true;81				}82			};83			if (project.Configuration.PauseOrDefault)84			{85				Console.Write("Press any key to start execution...");86				Console.ReadKey(true);87				Console.WriteLine();88			}89			if (project.Configuration.DebugOrDefault)90				Debugger.Launch();91			// We will enable "global" internal diagnostic messages if any test assembly wanted them92			globalInternalDiagnosticMessages = project.Assemblies.Any(a => a.Configuration.InternalDiagnosticMessagesOrDefault);93			noColor = project.Configuration.NoColorOrDefault;94			logger = new ConsoleRunnerLogger(!noColor, consoleLock);95			var diagnosticMessageSink = ConsoleDiagnosticMessageSink.ForInternalDiagnostics(consoleLock, globalInternalDiagnosticMessages, noColor);96			var reporter = project.RunnerReporter;97			var reporterMessageHandler = await reporter.CreateMessageHandler(logger, diagnosticMessageSink);98			if (!reporter.ForceNoLogo && !project.Configuration.NoLogoOrDefault)99				PrintHeader();100			var failCount = 0;101			if (project.Configuration.List != null)102				await ListProject(project);103			else104				failCount = await RunProject(project, reporterMessageHandler);105			if (cancel)106				return -1073741510;    // 0xC000013A: The application terminated as a result of a CTRL+C107			if (project.Configuration.WaitOrDefault)108			{109				Console.WriteLine();110				Console.Write("Press any key to continue...");111				Console.ReadKey();112				Console.WriteLine();113			}114			return project.Configuration.IgnoreFailures == true || failCount == 0 ? 0 : 1;115		}116		catch (Exception ex)117		{118			if (!noColor)119				ConsoleHelper.SetForegroundColor(ConsoleColor.Red);120			Console.WriteLine($"error: {ex.Message}");121			if (globalInternalDiagnosticMessages)122			{123				if (!noColor)124					ConsoleHelper.SetForegroundColor(ConsoleColor.DarkGray);125				Console.WriteLine(ex.StackTrace);126			}127			return ex is ArgumentException ? 3 : 4;128		}129		finally130		{131			if (!noColor)132				ConsoleHelper.ResetColor();133		}134	}135	void OnUnhandledException(136		object sender,137		UnhandledExceptionEventArgs e)138	{139		if (e.ExceptionObject is Exception ex)140			Console.WriteLine(ex.ToString());141		else142			Console.WriteLine("Error of unknown type thrown in application domain");143		Environment.Exit(1);144	}145	void PrintHeader() =>146		Console.WriteLine($"xUnit.net v3 In-Process Runner v{ThisAssembly.AssemblyInformationalVersion} ({IntPtr.Size * 8}-bit {RuntimeInformation.FrameworkDescription})");147	/// <summary>148	/// Creates a new <see cref="ConsoleRunner"/> instance and runs it via <see cref="EntryPoint"/>.149	/// </summary>150	/// <param name="args">The arguments passed to the application; typically pulled from the Main method.</param>151	/// <param name="testAssembly">The (optional) assembly to test; defaults to <see cref="Assembly.GetEntryAssembly"/>.</param>152	/// <param name="runnerReporters">The (optional) list of runner reporters.</param>153	/// <param name="consoleLock">The (optional) lock used around all console output to ensure there are no write collisions.</param>154	/// <returns>The return value intended to be returned by the Main method.</returns>155	public static ValueTask<int> Run(156		string[] args,157		Assembly? testAssembly = null,158		IEnumerable<IRunnerReporter>? runnerReporters = null,159		object? consoleLock = null) =>160			new ConsoleRunner(args, testAssembly, runnerReporters, consoleLock).EntryPoint();161	async ValueTask ListProject(XunitProject project)162	{163		var (listOption, listFormat) = project.Configuration.List!.Value;164		var testCasesByAssembly = new Dictionary<string, List<_ITestCase>>();165		foreach (var assembly in project.Assemblies)166		{167			var assemblyFileName = Guard.ArgumentNotNull(assembly.AssemblyFileName);168			// Default to false for console runners169			assembly.Configuration.PreEnumerateTheories ??= false;170			// Setup discovery options with command line overrides171			var discoveryOptions = _TestFrameworkOptions.ForDiscovery(assembly.Configuration);172			var assemblyDisplayName = assembly.AssemblyDisplayName;173			var noColor = assembly.Project.Configuration.NoColorOrDefault;174			var diagnosticMessageSink = ConsoleDiagnosticMessageSink.ForDiagnostics(consoleLock, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault, noColor);...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...6[assembly: CustomTestRunner(typeof(Xunit.Runner.TdNet.TdNetRunner))]7public class AutoGeneratedEntryPoint8{9	public static int Main(string[] args) =>10		ConsoleRunner.Run(args).GetAwaiter().GetResult();11}...

Full Screen

Full Screen

AutoGeneratedEntryPoint.cs

Source:AutoGeneratedEntryPoint.cs Github

copy

Full Screen

...9public class AutoGeneratedEntryPoint10{11	public static int Main(string[] args)12	{13		return ConsoleRunner.Run(args).GetAwaiter().GetResult();14	}15}...

Full Screen

Full Screen

ConsoleRunner

Using AI Code Generation

copy

Full Screen

1using Xunit.Runner.SystemConsole;2{3    static void Main(string[] args)4    {5        ConsoleRunner.RunAssembly(typeof(Program).Assembly, args);6    }7}8{9  "xunit": {10  }11}12using Xunit;13{14    public void TestMethod1()15    {16        Assert.True(false);17    }18}19{20  "xunit": {21  }22}

Full Screen

Full Screen

ConsoleRunner

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.Runner.SystemConsole;3{4    static void Main(string[] args)5    {6        var console = new ConsoleRunner(typeof(Program).Assembly);7        console.Run(args);8    }9}10using Xunit;11using Xunit.Runner.SystemConsole;12{13    static void Main(string[] args)14    {15        var console = new ConsoleRunner(typeof(Program).Assembly);16        console.Run(args);17    }18}19using Xunit;20using Xunit.Runner.SystemConsole;21{22    static void Main(string[] args)23    {24        var console = new ConsoleRunner(typeof(Program).Assembly);25        console.Run(args);26    }27}28using Xunit;29using Xunit.Runner.SystemConsole;30{31    static void Main(string[] args)32    {33        var console = new ConsoleRunner(typeof(Program).Assembly);34        console.Run(args);35    }36}37using Xunit;38using Xunit.Runner.SystemConsole;39{40    static void Main(string[] args)41    {42        var console = new ConsoleRunner(typeof(Program).Assembly);43        console.Run(args);44    }45}46using Xunit;47using Xunit.Runner.SystemConsole;48{49    static void Main(string[] args)50    {51        var console = new ConsoleRunner(typeof(Program).Assembly);52        console.Run(args);53    }54}55using Xunit;56using Xunit.Runner.SystemConsole;57{58    static void Main(string[] args)59    {60        var console = new ConsoleRunner(typeof(Program

Full Screen

Full Screen

ConsoleRunner

Using AI Code Generation

copy

Full Screen

1using Xunit.Runner.SystemConsole;2{3    {4        static void Main(string[] args)5        {6            var consoleRunner = new ConsoleRunner(typeof(Program).Assembly);7            consoleRunner.Run(args);8        }9    }10}11using Xunit;12{13    {14        public void Test1()15        {16            Assert.True(false);17        }18    }19}20using Xunit;21{22    {23        public void Test2()24        {25            Assert.True(true);26        }27    }28}29using Xunit;30{31    {32        public void Test3()33        {34            Assert.True(true);35        }36    }37}38using Xunit;39{40    {41        public void Test4()42        {43            Assert.True(true);44        }45    }46}47using Xunit;48{49    {50        public void Test5()51        {52            Assert.True(true);53        }54    }55}56using Xunit;57{58    {59        public void Test6()60        {61            Assert.True(true);62        }63    }64}65using Xunit;66{67    {68        public void Test7()69        {70            Assert.True(true);71        }72    }73}74using Xunit;75{76    {77        public void Test8()78        {79            Assert.True(true);80        }81    }82}83using Xunit;84{85    {86        public void Test9()87        {88            Assert.True(true);89        }90    }91}92using Xunit;

Full Screen

Full Screen

ConsoleRunner

Using AI Code Generation

copy

Full Screen

1using Xunit.Runner.SystemConsole;2{3    static int Main(string[] args)4    {5        return ConsoleRunner.Run(typeof(Program).Assembly, args);6    }7}8using Xunit;9{10    public void Test1()11    {12        Assert.True(true);13    }14}15Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "2", "2.csproj", "{7D0A6A0E-9E9A-4A2D-9B8C-1F4D4EFC7E97}"16Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "2.Tests", "2.Tests.csproj", "{C0E7C2D9-3D8C-4D3C-8D3C-8B8B9F9D7F7E}"17	GlobalSection(SolutionConfiguration

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Xunit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used methods in ConsoleRunner

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful