Best Xunit code snippet using Xunit.Runner.v2.DescriptorCallback.Callback
Xunit2.cs
Source:Xunit2.cs  
...126		public string TestFrameworkDisplayName => remoteDiscoverer.TestFrameworkDisplayName;127		List<KeyValuePair<string?, ITestCase?>> BulkDeserialize(List<string> serializations)128		{129			Guard.NotNull($"This instance of {typeof(Xunit2).FullName} was created for discovery only; execution-related operations cannot be performed.", remoteExecutor);130			var callbackContainer = new DeserializeCallback();131			Action<List<KeyValuePair<string?, ITestCase?>>> callback = callbackContainer.Callback;132			if (bulkDeserializer == null)133			{134				if (AppDomain.HasAppDomain)135				{136					try137					{138						AppDomain.CreateObject<object>(TestFrameworkAssemblyName, "Xunit.Sdk.TestCaseBulkDeserializer", remoteDiscoverer, remoteExecutor, serializations, callback);139						if (callbackContainer.Results != null)140							return callbackContainer.Results;141					}142					catch (TypeLoadException) { }    // Only be willing to eat "Xunit.Sdk.TestCaseBulkDeserialize" doesn't exist143				}144				bulkDeserializer = new DefaultTestCaseBulkDeserializer(remoteExecutor);145			}146			return bulkDeserializer.BulkDeserialize(serializations);147		}148		/// <summary>149		/// Creates a high performance cross-AppDomain message sink that utilizes <see cref="IMessageSinkWithTypes"/>150		/// which can be passed to <see cref="ITestFrameworkDiscoverer"/> and <see cref="ITestFrameworkExecutor"/>.151		/// </summary>152		/// <param name="sink">The local message sink to receive the messages.</param>153		/// <param name="serializeDiscoveredTestCases">A flag which indicates whether test case serialization is required</param>154		protected IMessageSink CreateOptimizedRemoteMessageSink(155			_IMessageSink sink,156			bool serializeDiscoveredTestCases = true)157		{158			Guard.ArgumentNotNull(sink);159			var v2MessageSink = new Xunit2MessageSink(sink, TestAssemblyUniqueID, serializeDiscoveredTestCases ? remoteDiscoverer : null);160			try161			{162				var asssemblyName = typeof(OptimizedRemoteMessageSink).Assembly.GetName();163				var optimizedSink = AppDomain.CreateObject<IMessageSink>(asssemblyName, typeof(OptimizedRemoteMessageSink).FullName!, v2MessageSink);164				if (optimizedSink != null)165					return optimizedSink;166			}167			catch { }    // This really shouldn't happen, but falling back makes sense in catastrophic cases168			return v2MessageSink;169		}170		/// <inheritdoc/>171		public virtual ValueTask DisposeAsync()172		{173			if (disposed)174				throw new ObjectDisposedException(GetType().FullName);175			disposed = true;176			return DisposalTracker.DisposeAsync();177		}178		/// <inheritdoc/>179		public void Find(180			_IMessageSink messageSink,181			FrontControllerFindSettings settings)182		{183			Guard.ArgumentNotNull(messageSink);184			Guard.ArgumentNotNull(settings);185			var includeSourceInformation = settings.Options.GetIncludeSourceInformationOrDefault();186			var filteringMessageSink = new FilteringMessageSink(messageSink, settings.Filters.Filter);187			// TODO: We're missing a potential optimization where we could determine that the filter188			// is exactly 1 (or maybe only?) "include class" filters, and then call the version of189			// Find on the remote discoverer that takes a type name.190			SendDiscoveryStartingMessage(messageSink);191			remoteDiscoverer.Find(192				includeSourceInformation,193				CreateOptimizedRemoteMessageSink(filteringMessageSink),194				Xunit2OptionsAdapter.Adapt(settings.Options)195			);196		}197		/// <inheritdoc/>198		public void FindAndRun(199			_IMessageSink messageSink,200			FrontControllerFindAndRunSettings settings)201		{202			Guard.NotNull($"This instance of {typeof(Xunit2).FullName} was created for discovery only; execution-related operations cannot be performed.", remoteExecutor);203			Guard.ArgumentNotNull(messageSink);204			Guard.ArgumentNotNull(settings);205			if (settings.Filters.Empty)206			{207				remoteExecutor.RunAll(208					CreateOptimizedRemoteMessageSink(messageSink),209					Xunit2OptionsAdapter.Adapt(settings.DiscoveryOptions),210					Xunit2OptionsAdapter.Adapt(settings.ExecutionOptions)211				);212				return;213			}214			using var discoverySink = new Xunit2DiscoverySink(settings.Filters);215			remoteDiscoverer.Find(216				includeSourceInformation: false,217				discoverySink,218				Xunit2OptionsAdapter.Adapt(settings.DiscoveryOptions)219			);220			discoverySink.Finished.WaitOne();221			remoteExecutor.RunTests(222				discoverySink.TestCases,223				CreateOptimizedRemoteMessageSink(messageSink),224				Xunit2OptionsAdapter.Adapt(settings.ExecutionOptions)225			);226		}227		static string GetExecutionAssemblyFileName(AppDomainSupport appDomainSupport, string basePath)228		{229			var supportedPlatformSuffixes = GetSupportedPlatformSuffixes(appDomainSupport);230			foreach (var suffix in supportedPlatformSuffixes)231			{232#if NETFRAMEWORK233				var fileName = Path.Combine(basePath, $"xunit.execution.{suffix}.dll");234				if (File.Exists(fileName))235					return fileName;236#else237				try238				{239					var assemblyName = $"xunit.execution.{suffix}";240					Assembly.Load(new AssemblyName { Name = assemblyName });241					return assemblyName + ".dll";242				}243				catch { }244#endif245			}246			throw new InvalidOperationException("Could not find/load any of the following assemblies: " + string.Join(", ", supportedPlatformSuffixes.Select(suffix => $"xunit.execution.{suffix}.dll").ToArray()));247		}248		static string[] GetSupportedPlatformSuffixes(AppDomainSupport appDomainSupport)249		{250#if NETFRAMEWORK251			return appDomainSupport == AppDomainSupport.Required ? SupportedPlatforms_ForcedAppDomains : SupportedPlatforms;252#else253			return SupportedPlatforms;254#endif255		}256		static AssemblyName GetTestFrameworkAssemblyName(string xunitExecutionAssemblyPath)257		{258#if NETFRAMEWORK259			return AssemblyName.GetAssemblyName(xunitExecutionAssemblyPath);260#else261			// Make sure we only use the short form262			return Assembly.Load(new AssemblyName { Name = Path.GetFileNameWithoutExtension(xunitExecutionAssemblyPath), Version = new Version(0, 0, 0, 0) }).GetName();263#endif264		}265		static string GetXunitExecutionAssemblyPath(266			AppDomainSupport appDomainSupport,267			string assemblyFileName,268			bool verifyTestAssemblyExists)269		{270			Guard.ArgumentNotNullOrEmpty(assemblyFileName);271			if (verifyTestAssemblyExists)272				Guard.FileExists(assemblyFileName);273			return GetExecutionAssemblyFileName(appDomainSupport, Path.GetDirectoryName(assemblyFileName)!);274		}275		static string GetXunitExecutionAssemblyPath(276			AppDomainSupport appDomainSupport,277			_IAssemblyInfo assemblyInfo)278		{279			Guard.ArgumentNotNull(assemblyInfo);280			Guard.ArgumentNotNullOrEmpty(assemblyInfo.AssemblyPath);281			return GetExecutionAssemblyFileName(appDomainSupport, Path.GetDirectoryName(assemblyInfo.AssemblyPath)!);282		}283#if NETFRAMEWORK284		static bool IsDotNet(string executionAssemblyFileName) =>285			executionAssemblyFileName.EndsWith(".dotnet.dll", StringComparison.Ordinal);286#endif287		/// <inheritdoc/>288		public void Run(289			_IMessageSink messageSink,290			FrontControllerRunSettings settings)291		{292			Guard.NotNull($"This instance of {typeof(Xunit2).FullName} was created for discovery only; execution-related operations cannot be performed.", remoteExecutor);293			Guard.ArgumentNotNull(messageSink);294			Guard.ArgumentNotNull(settings);295			remoteExecutor.RunTests(296				BulkDeserialize(settings.SerializedTestCases.ToList()).Select(kvp => kvp.Value).ToList(),297				CreateOptimizedRemoteMessageSink(messageSink),298				Xunit2OptionsAdapter.Adapt(settings.Options)299			);300		}301		void SendDiscoveryStartingMessage(_IMessageSink messageSink)302		{303			// There is no v2 equivalent to this, so we manufacture it ourselves304			var discoveryStarting = new _DiscoveryStarting305			{306				AssemblyName = assemblyInfo.Name,307				AssemblyPath = assemblyInfo.AssemblyPath,308				AssemblyUniqueID = UniqueIDGenerator.ForAssembly(assemblyInfo.Name, assemblyInfo.AssemblyPath, configFileName),309				ConfigFilePath = configFileName310			};311			messageSink.OnMessage(discoveryStarting);312		}313		// Factory methods314		/// <summary>315		/// Returns an implementation of <see cref="IFrontControllerDiscoverer"/> which can be used316		/// to discover xUnit.net v2 tests, including source-based discovery.317		/// </summary>318		/// <param name="assemblyInfo">The assembly to use for discovery</param>319		/// <param name="projectAssembly">The test project assembly.</param>320		/// <param name="xunitExecutionAssemblyPath">The path on disk of xunit.execution.*.dll; if <c>null</c>, then321		/// the location of xunit.execution.*.dll is implied based on the location of the test assembly</param>322		/// <param name="sourceInformationProvider">The optional source information provider.</param>323		/// <param name="diagnosticMessageSink">The message sink which receives <see cref="_DiagnosticMessage"/> messages.</param>324		/// <param name="verifyAssembliesOnDisk">Determines whether or not to check for the existence of assembly files.</param>325		public static IFrontControllerDiscoverer ForDiscovery(326			_IAssemblyInfo assemblyInfo,327			XunitProjectAssembly projectAssembly,328			string? xunitExecutionAssemblyPath = null,329			_ISourceInformationProvider? sourceInformationProvider = null,330			_IMessageSink? diagnosticMessageSink = null,331			bool verifyAssembliesOnDisk = true)332		{333			var appDomainSupport = projectAssembly.Configuration.AppDomainOrDefault;334			Guard.ArgumentNotNull(assemblyInfo);335			return new Xunit2(336				diagnosticMessageSink ?? _NullMessageSink.Instance,337				appDomainSupport,338				sourceInformationProvider ?? _NullSourceInformationProvider.Instance,  // TODO: Need to find a way to be able to use VisualStudioSourceInformationProvider339				assemblyInfo,340				assemblyFileName: null,341				xunitExecutionAssemblyPath ?? GetXunitExecutionAssemblyPath(appDomainSupport, assemblyInfo),342				projectAssembly.ConfigFileName,343				projectAssembly.Configuration.ShadowCopyOrDefault,344				projectAssembly.Configuration.ShadowCopyFolder,345				verifyAssembliesOnDisk346			);347		}348		/// <summary>349		/// Returns an implementation of <see cref="IFrontController"/> which can be used350		/// for both discovery and execution of xUnit.net v2 tests.351		/// </summary>352		/// <param name="projectAssembly">The test project assembly.</param>353		/// <param name="sourceInformationProvider">The optional source information provider.</param>354		/// <param name="diagnosticMessageSink">The message sink which receives <see cref="_DiagnosticMessage"/> messages.</param>355		/// <param name="verifyAssembliesOnDisk">Determines whether or not to check for the existence of assembly files.</param>356		public static IFrontController ForDiscoveryAndExecution(357			XunitProjectAssembly projectAssembly,358			_ISourceInformationProvider? sourceInformationProvider = null,359			_IMessageSink? diagnosticMessageSink = null,360			bool verifyAssembliesOnDisk = true)361		{362			Guard.ArgumentNotNull(projectAssembly);363			var appDomainSupport = projectAssembly.Configuration.AppDomainOrDefault;364			var assemblyFileName = Guard.ArgumentNotNull(projectAssembly.AssemblyFileName);365			if (diagnosticMessageSink == null)366				diagnosticMessageSink = _NullMessageSink.Instance;367			return new Xunit2(368				diagnosticMessageSink,369				appDomainSupport,370#if NETSTANDARD371				sourceInformationProvider ?? _NullSourceInformationProvider.Instance,372#else373				sourceInformationProvider ?? new VisualStudioSourceInformationProvider(assemblyFileName, diagnosticMessageSink),374#endif375				assemblyInfo: null,376				assemblyFileName,377				GetXunitExecutionAssemblyPath(appDomainSupport, assemblyFileName, verifyAssembliesOnDisk),378				projectAssembly.ConfigFileName,379				projectAssembly.Configuration.ShadowCopyOrDefault,380				projectAssembly.Configuration.ShadowCopyFolder,381				verifyAssembliesOnDisk382			);383		}384		// Inner classes385		class DescriptorCallback : LongLivedMarshalByRefObject386		{387			public List<string>? Results;388			public void Callback(List<string> results) => Results = results;389		}390		class DeserializeCallback : LongLivedMarshalByRefObject391		{392			public List<KeyValuePair<string?, ITestCase?>>? Results;393			public void Callback(List<KeyValuePair<string?, ITestCase?>> results) => Results = results;394		}395		class FilteringMessageSink : _IMessageSink396		{397			readonly Predicate<_TestCaseDiscovered> filter;398			readonly _IMessageSink innerMessageSink;399			public FilteringMessageSink(400				_IMessageSink innerMessageSink,401				Predicate<_TestCaseDiscovered> filter)402			{403				this.innerMessageSink = innerMessageSink;404				this.filter = filter;405			}406			public bool OnMessage(_MessageSinkMessage message)407			{...Xunit2Discoverer.cs
Source:Xunit2Discoverer.cs  
...160        }161        /// <inheritdoc/>162        public List<TestCaseDescriptor> GetTestCaseDescriptors(List<ITestCase> testCases, bool includeSerialization)163        {164            var callbackContainer = new DescriptorCallback();165            Action<List<string>> callback = callbackContainer.Callback;166            if (defaultTestCaseDescriptorProvider == null)167            {168                if (AppDomain.HasAppDomain)169                {170                    try171                    {172                        AppDomain.CreateObject<object>(TestFrameworkAssemblyName, "Xunit.Sdk.TestCaseDescriptorFactory", includeSerialization ? RemoteDiscoverer : null, testCases, callback);173                        if (callbackContainer.Results != null)174                            return callbackContainer.Results.Select(x => new TestCaseDescriptor(x)).ToList();175                    }176                    catch (TypeLoadException) { }    // Only be willing to eat "Xunit.Sdk.TestCaseDescriptorFactory" doesn't exist177                }178                defaultTestCaseDescriptorProvider = new DefaultTestCaseDescriptorProvider(RemoteDiscoverer);179            }180            return defaultTestCaseDescriptorProvider.GetTestCaseDescriptors(testCases, includeSerialization);181        }182        static string GetExecutionAssemblyFileName(AppDomainSupport appDomainSupport, string basePath)183        {184            var supportedPlatformSuffixes = GetSupportedPlatformSuffixes(appDomainSupport);185            foreach (var suffix in supportedPlatformSuffixes)186            {187#if NET35 || NET452188                var fileName = Path.Combine(basePath, $"xunit.execution.{suffix}.dll");189                if (File.Exists(fileName))190                    return fileName;191#else192                try193                {194                    var assemblyName = $"xunit.execution.{suffix}";195                    Assembly.Load(new AssemblyName { Name = assemblyName });196                    return assemblyName + ".dll";197                }198                catch { }199#endif200            }201            throw new InvalidOperationException("Could not find/load any of the following assemblies: " + string.Join(", ", supportedPlatformSuffixes.Select(suffix => $"xunit.execution.{suffix}.dll").ToArray()));202        }203        static string[] GetSupportedPlatformSuffixes(AppDomainSupport appDomainSupport)204        {205#if NET35 || NET452206            return appDomainSupport == AppDomainSupport.Required ? SupportedPlatforms_ForcedAppDomains : SupportedPlatforms;207#else208            return SupportedPlatforms;209#endif210        }211        static AssemblyName GetTestFrameworkAssemblyName(string xunitExecutionAssemblyPath)212        {213#if NET35 || NET452214            return AssemblyName.GetAssemblyName(xunitExecutionAssemblyPath);215#elif NETCOREAPP1_0216            return new AssemblyName(Path.GetFileNameWithoutExtension(xunitExecutionAssemblyPath));217#else218            // Make sure we only use the short form219            return Assembly.Load(new AssemblyName { Name = Path.GetFileNameWithoutExtension(xunitExecutionAssemblyPath), Version = new Version(0, 0, 0, 0) }).GetName();220#endif221        }222        static string GetXunitExecutionAssemblyPath(AppDomainSupport appDomainSupport, string assemblyFileName, bool verifyTestAssemblyExists)223        {224            Guard.ArgumentNotNullOrEmpty("assemblyFileName", assemblyFileName);225            if (verifyTestAssemblyExists)226                Guard.FileExists("assemblyFileName", assemblyFileName);227            return GetExecutionAssemblyFileName(appDomainSupport, Path.GetDirectoryName(assemblyFileName));228        }229        static string GetXunitExecutionAssemblyPath(AppDomainSupport appDomainSupport, IAssemblyInfo assemblyInfo)230        {231            Guard.ArgumentNotNull("assemblyInfo", assemblyInfo);232            Guard.ArgumentNotNullOrEmpty("assemblyInfo.AssemblyPath", assemblyInfo.AssemblyPath);233            return GetExecutionAssemblyFileName(appDomainSupport, Path.GetDirectoryName(assemblyInfo.AssemblyPath));234        }235        static bool IsDotNet(string executionAssemblyFileName)236            => executionAssemblyFileName.EndsWith(".dotnet.dll", StringComparison.Ordinal);237        /// <inheritdoc/>238        public string Serialize(ITestCase testCase)239            => RemoteDiscoverer.Serialize(testCase);240        class DescriptorCallback : LongLivedMarshalByRefObject241        {242            public List<string> Results;243            public void Callback(List<string> results) => Results = results;244        }245    }246}...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
