Best Xunit code snippet using Xunit.v3.Mocks.MethodInfo
Mocks.cs
Source:Mocks.cs
...143 if (attributeType == null)144 return Enumerable.Empty<IAttributeInfo>();145 return attributes.Where(attribute => attributeType.IsAssignableFrom(attribute.Attribute.GetType())).ToList();146 }147 public static IMethodInfo MethodInfo(148 string? methodName = null,149 IReflectionAttributeInfo[]? attributes = null,150 IParameterInfo[]? parameters = null,151 ITypeInfo? type = null,152 ITypeInfo? returnType = null,153 bool isAbstract = false,154 bool isPublic = true,155 bool isStatic = false)156 {157 var result = Substitute.For<IMethodInfo, InterfaceProxy<IMethodInfo>>();158 attributes ??= new IReflectionAttributeInfo[0];159 parameters ??= new IParameterInfo[0];160 result.IsAbstract.Returns(isAbstract);161 result.IsPublic.Returns(isPublic);162 result.IsStatic.Returns(isStatic);163 result.Name.Returns(methodName ?? "method:" + Guid.NewGuid().ToString("n"));164 result.ReturnType.Returns(returnType);165 result.Type.Returns(type);166 result.GetCustomAttributes("").ReturnsForAnyArgs(callInfo => LookupAttribute(callInfo.Arg<string>(), attributes));167 result.GetParameters().Returns(parameters);168 return result;169 }170 public static IParameterInfo ParameterInfo(string name)171 {172 var result = Substitute.For<IParameterInfo, InterfaceProxy<IParameterInfo>>();173 result.Name.Returns(name);174 return result;175 }176 public static IReflectionMethodInfo ReflectionMethodInfo<TClass>(string methodName)177 {178 return Reflector.Wrap(typeof(TClass).GetMethod(methodName)!);179 }180 public static IReflectionTypeInfo ReflectionTypeInfo<TClass>()181 {182 return Reflector.Wrap(typeof(TClass));183 }184 public static IRunnerReporter RunnerReporter(185 string? runnerSwitch = null,186 string? description = null,187 bool isEnvironmentallyEnabled = false,188 IMessageSinkWithTypes? messageSink = null)189 {190 var result = Substitute.For<IRunnerReporter, InterfaceProxy<IRunnerReporter>>();191 result.Description.Returns(description ?? "The runner reporter description");192 result.IsEnvironmentallyEnabled.ReturnsForAnyArgs(isEnvironmentallyEnabled);193 result.RunnerSwitch.Returns(runnerSwitch);194 var dualSink = MessageSinkAdapter.Wrap(messageSink ?? Substitute.For<IMessageSinkWithTypes, InterfaceProxy<IMessageSinkWithTypes>>());195 result.CreateMessageHandler(null!).ReturnsForAnyArgs(dualSink);196 return result;197 }198 public static ITest Test(199 ITestCase testCase,200 string displayName)201 {202 var result = Substitute.For<ITest, InterfaceProxy<ITest>>();203 result.DisplayName.Returns(displayName);204 result.TestCase.Returns(testCase);205 return result;206 }207 public static ITestAssembly TestAssembly(IReflectionAttributeInfo[] attributes)208 {209 var assemblyInfo = AssemblyInfo(attributes: attributes);210 var result = Substitute.For<ITestAssembly, InterfaceProxy<ITestAssembly>>();211 result.Assembly.Returns(assemblyInfo);212 return result;213 }214 public static ITestAssembly TestAssembly(215 string assemblyFileName,216 string? configFileName = null,217 ITypeInfo[]? types = null,218 IReflectionAttributeInfo[]? attributes = null)219 {220 var assemblyInfo = AssemblyInfo(types, attributes, assemblyFileName);221 var result = Substitute.For<ITestAssembly, InterfaceProxy<ITestAssembly>>();222 result.Assembly.Returns(assemblyInfo);223 result.ConfigFileName.Returns(configFileName);224 return result;225 }226 public static TestAssembly TestAssembly(227 Assembly? assembly = null,228 string? configFileName = null)229 {230#if NETFRAMEWORK231 if (configFileName == null)232 configFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;233#endif234 return new TestAssembly(Reflector.Wrap(assembly ?? typeof(Mocks).Assembly), configFileName);235 }236 public static ITestAssemblyDiscoveryFinished TestAssemblyDiscoveryFinished(237 bool diagnosticMessages = false,238 int toRun = 42,239 int discovered = 2112)240 {241 var assembly = new XunitProjectAssembly { AssemblyFilename = "testAssembly.dll", ConfigFilename = "testAssembly.dll.config" };242 var config = new TestAssemblyConfiguration { DiagnosticMessages = diagnosticMessages, ShadowCopy = true };243 var result = Substitute.For<ITestAssemblyDiscoveryFinished, InterfaceProxy<ITestAssemblyDiscoveryFinished>>();244 result.Assembly.Returns(assembly);245 result.DiscoveryOptions.Returns(TestFrameworkOptions.ForDiscovery(config));246 result.TestCasesDiscovered.Returns(discovered);247 result.TestCasesToRun.Returns(toRun);248 return result;249 }250 public static ITestAssemblyDiscoveryStarting TestAssemblyDiscoveryStarting(251 bool diagnosticMessages = false,252 AppDomainOption appDomain = AppDomainOption.Disabled,253 bool shadowCopy = false)254 {255 var assembly = new XunitProjectAssembly { AssemblyFilename = "testAssembly.dll", ConfigFilename = "testAssembly.dll.config" };256 var config = new TestAssemblyConfiguration { DiagnosticMessages = diagnosticMessages, MethodDisplay = Xunit.TestMethodDisplay.ClassAndMethod, MaxParallelThreads = 42, ParallelizeTestCollections = true, ShadowCopy = shadowCopy };257 var result = Substitute.For<ITestAssemblyDiscoveryStarting, InterfaceProxy<ITestAssemblyDiscoveryStarting>>();258 result.AppDomain.Returns(appDomain);259 result.Assembly.Returns(assembly);260 result.DiscoveryOptions.Returns(TestFrameworkOptions.ForDiscovery(config));261 result.ShadowCopy.Returns(shadowCopy);262 return result;263 }264 public static ITestAssemblyExecutionFinished TestAssemblyExecutionFinished(265 bool diagnosticMessages = false,266 int total = 2112,267 int failed = 42,268 int skipped = 8,269 int errors = 6,270 decimal time = 123.456M)271 {272 var assembly = new XunitProjectAssembly { AssemblyFilename = "testAssembly.dll", ConfigFilename = "testAssembly.dll.config" };273 var config = new TestAssemblyConfiguration { DiagnosticMessages = diagnosticMessages, ShadowCopy = true };274 var summary = new ExecutionSummary { Total = total, Failed = failed, Skipped = skipped, Errors = errors, Time = time };275 var result = Substitute.For<ITestAssemblyExecutionFinished, InterfaceProxy<ITestAssemblyExecutionFinished>>();276 result.Assembly.Returns(assembly);277 result.ExecutionOptions.Returns(TestFrameworkOptions.ForExecution(config));278 result.ExecutionSummary.Returns(summary);279 return result;280 }281 public static ITestAssemblyExecutionStarting TestAssemblyExecutionStarting(282 bool diagnosticMessages = false,283 string? assemblyFilename = null)284 {285 var assembly = new XunitProjectAssembly { AssemblyFilename = assemblyFilename ?? "testAssembly.dll", ConfigFilename = "testAssembly.dll.config" };286 var config = new TestAssemblyConfiguration { DiagnosticMessages = diagnosticMessages, MethodDisplay = Xunit.TestMethodDisplay.ClassAndMethod, MaxParallelThreads = 42, ParallelizeTestCollections = true, ShadowCopy = true };287 var result = Substitute.For<ITestAssemblyExecutionStarting, InterfaceProxy<ITestAssemblyExecutionStarting>>();288 result.Assembly.Returns(assembly);289 result.ExecutionOptions.Returns(TestFrameworkOptions.ForExecution(config));290 return result;291 }292 public static ITestAssemblyFinished TestAssemblyFinished(293 int testsRun = 2112,294 int testsFailed = 42,295 int testsSkipped = 6,296 decimal executionTime = 123.4567M)297 {298 var testAssembly = TestAssembly("testAssembly.dll");299 var result = Substitute.For<ITestAssemblyFinished, InterfaceProxy<ITestAssemblyFinished>>();300 result.TestAssembly.Returns(testAssembly);301 result.TestsRun.Returns(testsRun);302 result.TestsFailed.Returns(testsFailed);303 result.TestsSkipped.Returns(testsSkipped);304 result.ExecutionTime.Returns(executionTime);305 return result;306 }307 public static ITestAssemblyStarting TestAssemblyStarting()308 {309 var testAssembly = TestAssembly("testAssembly.dll");310 var result = Substitute.For<ITestAssemblyStarting, InterfaceProxy<ITestAssemblyStarting>>();311 result.TestAssembly.Returns(testAssembly);312 return result;313 }314 public static ITestCase TestCase(ITestCollection? collection = null)315 {316 if (collection == null)317 collection = TestCollection();318 var result = Substitute.For<ITestCase, InterfaceProxy<ITestCase>>();319 result.TestMethod.TestClass.TestCollection.Returns(collection);320 return result;321 }322 public static ITestCase TestCase(ITestMethod testMethod)323 {324 var result = Substitute.For<ITestCase, InterfaceProxy<ITestCase>>();325 result.TestMethod.Returns(testMethod);326 return result;327 }328 public static ITestCase TestCase<TClassUnderTest>(329 string methodName,330 string? displayName = null,331 string? skipReason = null,332 string? uniqueID = null,333 string? fileName = null,334 int? lineNumber = null)335 {336 return TestCase(typeof(TClassUnderTest), methodName, displayName, skipReason, uniqueID, fileName, lineNumber);337 }338 public static ITestCase TestCase(339 Type type,340 string methodName,341 string? displayName = null,342 string? skipReason = null,343 string? uniqueID = null,344 string? fileName = null,345 int? lineNumber = null)346 {347 var testMethod = TestMethod(type, methodName);348 var traits = GetTraits(testMethod.Method);349 var result = Substitute.For<ITestCase, InterfaceProxy<ITestCase>>();350 result.DisplayName.Returns(displayName ?? $"{type}.{methodName}");351 result.SkipReason.Returns(skipReason);352 result.TestMethod.Returns(testMethod);353 result.Traits.Returns(traits);354 result.UniqueID.Returns(uniqueID ?? Guid.NewGuid().ToString());355 if (fileName != null && lineNumber != null)356 {357 var sourceInfo = new Xunit.SourceInformation { FileName = fileName, LineNumber = lineNumber };358 result.SourceInformation.Returns(sourceInfo);359 }360 return result;361 }362 public static IReflectionAttributeInfo TestCaseOrdererAttribute(string typeName, string assemblyName)363 {364 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();365 result.Attribute.Returns(new TestCaseOrdererAttribute(typeName, assemblyName));366 result.GetConstructorArguments().Returns(new object[] { typeName, assemblyName });367 return result;368 }369 public static IReflectionAttributeInfo TestCaseOrdererAttribute(Type type)370 {371 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();372 result.Attribute.Returns(new TestCaseOrdererAttribute(type));373 result.GetConstructorArguments().Returns(new object[] { type });374 return result;375 }376 public static IReflectionAttributeInfo TestCaseOrdererAttribute<TOrderer>() =>377 TestCaseOrdererAttribute(typeof(TOrderer));378 public static ITestClass TestClass(379 string? typeName = null,380 IReflectionAttributeInfo[]? attributes = null)381 {382 var testCollection = TestCollection();383 var typeInfo = TypeInfo(typeName, attributes: attributes);384 var result = Substitute.For<ITestClass, InterfaceProxy<ITestClass>>();385 result.Class.Returns(typeInfo);386 result.TestCollection.Returns(testCollection);387 return result;388 }389 public static TestClass TestClass(390 Type type,391 ITestCollection? collection = null)392 {393 if (collection == null)394 collection = TestCollection(type.Assembly);395 return new TestClass(collection, Reflector.Wrap(type));396 }397 public static TestCollection TestCollection(398 Assembly? assembly = null,399 ITypeInfo? definition = null,400 string? displayName = null)401 {402 if (assembly == null)403 assembly = typeof(Mocks).Assembly;404 if (displayName == null)405 displayName = "Mock test collection for " + assembly.CodeBase;406 return new TestCollection(TestAssembly(assembly), definition, displayName);407 }408 public static ITestCollectionFinished TestCollectionFinished(409 string displayName = "Display Name",410 int testsRun = 2112,411 int testsFailed = 42,412 int testsSkipped = 6,413 decimal executionTime = 123.4567M)414 {415 var result = Substitute.For<ITestCollectionFinished, InterfaceProxy<ITestCollectionFinished>>();416 result.TestsRun.Returns(testsRun);417 result.TestsFailed.Returns(testsFailed);418 result.TestsSkipped.Returns(testsSkipped);419 result.ExecutionTime.Returns(executionTime);420 result.TestCollection.DisplayName.Returns(displayName);421 return result;422 }423 public static ITestCollectionStarting TestCollectionStarting()424 {425 var result = Substitute.For<ITestCollectionStarting, InterfaceProxy<ITestCollectionStarting>>();426 result.TestCollection.DisplayName.Returns("Display Name");427 return result;428 }429 public static IReflectionAttributeInfo TestCollectionOrdererAttribute(string typeName, string assemblyName)430 {431 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();432 result.Attribute.Returns(new TestCollectionOrdererAttribute(typeName, assemblyName));433 result.GetConstructorArguments().Returns(new object[] { typeName, assemblyName });434 return result;435 }436 public static IReflectionAttributeInfo TestCollectionOrdererAttribute(Type type)437 {438 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();439 result.Attribute.Returns(new TestCollectionOrdererAttribute(type));440 result.GetConstructorArguments().Returns(new object[] { type });441 return result;442 }443 public static IReflectionAttributeInfo TestCollectionOrdererAttribute<TOrderer>() =>444 TestCollectionOrdererAttribute(typeof(TOrderer));445 public static ITestFailed TestFailed(446 Type type,447 string methodName,448 string? displayName = null,449 string? output = null,450 decimal executionTime = 0M,451 Exception? ex = null)452 {453 var testCase = TestCase(type, methodName);454 var test = Test(testCase, displayName ?? "NO DISPLAY NAME");455 var failureInfo = Xunit.Sdk.ExceptionUtility.ConvertExceptionToFailureInformation(ex ?? new Exception());456 var result = Substitute.For<ITestFailed, InterfaceProxy<ITestFailed>>();457 result.ExceptionParentIndices.Returns(failureInfo.ExceptionParentIndices);458 result.ExceptionTypes.Returns(failureInfo.ExceptionTypes);459 result.ExecutionTime.Returns(executionTime);460 result.Messages.Returns(failureInfo.Messages);461 result.Output.Returns(output);462 result.StackTraces.Returns(failureInfo.StackTraces);463 result.TestCase.Returns(testCase);464 result.Test.Returns(test);465 return result;466 }467 public static ITestFailed TestFailed(468 string displayName,469 decimal executionTime,470 string? exceptionType = null,471 string? exceptionMessage = null,472 string? stackTrace = null,473 string? output = null)474 {475 var testCase = TestCase();476 var test = Test(testCase, displayName);477 var result = Substitute.For<ITestFailed, InterfaceProxy<ITestFailed>>();478 result.ExceptionParentIndices.Returns(new[] { -1 });479 result.ExceptionTypes.Returns(new[] { exceptionType });480 result.ExecutionTime.Returns(executionTime);481 result.Messages.Returns(new[] { exceptionMessage });482 result.Output.Returns(output);483 result.StackTraces.Returns(new[] { stackTrace });484 result.TestCase.Returns(testCase);485 result.Test.Returns(test);486 return result;487 }488 public static IReflectionAttributeInfo TestFrameworkAttribute(Type type)489 {490 var attribute = Activator.CreateInstance(type);491 if (attribute == null)492 throw new InvalidOperationException($"Unable to create attribute instance: '{type.FullName}'");493 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();494 result.Attribute.Returns(attribute);495 result.GetCustomAttributes(null).ReturnsForAnyArgs(496 callInfo => LookupAttribute(497 callInfo.Arg<string>(),498 CustomAttributeData.GetCustomAttributes(attribute.GetType()).Select(x => Reflector.Wrap(x)).ToArray()499 )500 );501 return result;502 }503 public static ITestMethod TestMethod(504 string? typeName = null,505 string? methodName = null,506 string? displayName = null,507 string? skip = null,508 int timeout = 0,509 IEnumerable<IParameterInfo>? parameters = null,510 IEnumerable<IReflectionAttributeInfo>? classAttributes = null,511 IEnumerable<IReflectionAttributeInfo>? methodAttributes = null)512 {513 if (classAttributes == null)514 classAttributes = Enumerable.Empty<IReflectionAttributeInfo>();515 if (methodAttributes == null)516 methodAttributes = Enumerable.Empty<IReflectionAttributeInfo>();517 if (parameters == null)518 parameters = Enumerable.Empty<IParameterInfo>();519 var factAttribute = methodAttributes.FirstOrDefault(attr => typeof(FactAttribute).IsAssignableFrom(attr.Attribute.GetType()));520 if (factAttribute == null)521 {522 factAttribute = FactAttribute(displayName, skip, timeout);523 methodAttributes = methodAttributes.Concat(new[] { factAttribute });524 }525 var testClass = TestClass(typeName, attributes: classAttributes.ToArray());526 var methodInfo = MethodInfo(methodName, methodAttributes.ToArray(), parameters.ToArray(), testClass.Class);527 var result = Substitute.For<ITestMethod, InterfaceProxy<ITestMethod>>();528 result.Method.Returns(methodInfo);529 result.TestClass.Returns(testClass);530 return result;531 }532 public static TestMethod TestMethod(533 Type type,534 string methodName,535 ITestCollection? collection = null)536 {537 var @class = TestClass(type, collection);538 var methodInfo = type.GetMethod(methodName);539 if (methodInfo == null)540 throw new Exception($"Unknown method: {type.FullName}.{methodName}");541 return new TestMethod(@class, Reflector.Wrap(methodInfo));542 }543 public static ITestPassed TestPassed(544 Type type,545 string methodName,546 string? displayName = null,547 string? output = null,548 decimal executionTime = 0M)549 {550 var testCase = TestCase(type, methodName);551 var test = Test(testCase, displayName ?? "NO DISPLAY NAME");552 var result = Substitute.For<ITestPassed, InterfaceProxy<ITestPassed>>();553 result.ExecutionTime.Returns(executionTime);554 result.Output.Returns(output);555 result.TestCase.Returns(testCase);556 result.Test.Returns(test);557 return result;558 }559 public static ITestPassed TestPassed(560 string displayName,561 string? output = null)562 {563 var testCase = TestCase();564 var test = Test(testCase, displayName);565 var result = Substitute.For<ITestPassed, InterfaceProxy<ITestPassed>>();566 result.Test.Returns(test);567 result.ExecutionTime.Returns(1.2345M);568 result.Output.Returns(output);569 return result;570 }571 public static ITestResultMessage TestResult<TClassUnderTest>(572 string methodName,573 string displayName,574 decimal executionTime)575 {576 var testCase = TestCase<TClassUnderTest>(methodName);577 var test = Test(testCase, displayName);578 var result = Substitute.For<ITestResultMessage, InterfaceProxy<ITestResultMessage>>();579 result.TestCase.Returns(testCase);580 result.Test.Returns(test);581 result.ExecutionTime.Returns(executionTime);582 return result;583 }584 public static ITestSkipped TestSkipped(585 Type type,586 string methodName,587 string? displayName = null,588 string? output = null,589 decimal executionTime = 0M,590 string? skipReason = null)591 {592 var testCase = TestCase(type, methodName);593 var test = Test(testCase, displayName ?? "NO DISPLAY NAME");594 var result = Substitute.For<ITestSkipped, InterfaceProxy<ITestSkipped>>();595 result.ExecutionTime.Returns(executionTime);596 result.Output.Returns(output);597 result.Reason.Returns(skipReason);598 result.TestCase.Returns(testCase);599 result.Test.Returns(test);600 return result;601 }602 public static ITestSkipped TestSkipped(603 string displayName,604 string? skipReason = null)605 {606 var testCase = TestCase();607 var test = Test(testCase, displayName);608 var result = Substitute.For<ITestSkipped, InterfaceProxy<ITestSkipped>>();609 result.Reason.Returns(skipReason);610 result.TestCase.Returns(testCase);611 result.Test.Returns(test);612 return result;613 }614 public static ITestStarting TestStarting(string displayName)615 {616 var testCase = TestCase();617 var test = Test(testCase, displayName);618 var result = Substitute.For<ITestStarting, InterfaceProxy<ITestStarting>>();619 result.Test.Returns(test);620 return result;621 }622 public static IReflectionAttributeInfo TheoryAttribute(623 string? displayName = null,624 string? skip = null,625 int timeout = 0)626 {627 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();628 result.Attribute.Returns(new TheoryAttribute { DisplayName = displayName, Skip = skip });629 result.GetNamedArgument<string>("DisplayName").Returns(displayName);630 result.GetNamedArgument<string>("Skip").Returns(skip);631 result.GetNamedArgument<int>("Timeout").Returns(timeout);632 return result;633 }634 public static IReflectionAttributeInfo TraitAttribute<T>()635 where T : Attribute, new()636 {637 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();638 result.Attribute.Returns(new T());639 return result;640 }641 public static IReflectionAttributeInfo TraitAttribute(642 string name,643 string value)644 {645 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();646 var traitDiscovererAttributes = new[] { TraitDiscovererAttribute() };647 result.GetCustomAttributes(typeof(TraitDiscovererAttribute)).Returns(traitDiscovererAttributes);648 result.Attribute.Returns(new TraitAttribute(name, value));649 result.GetConstructorArguments().Returns(new object[] { name, value });650 return result;651 }652 public static IAttributeInfo TraitDiscovererAttribute(653 string typeName = "Xunit.Sdk.TraitDiscoverer",654 string assemblyName = "xunit.v3.core")655 {656 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();657 result.Attribute.Returns(new TraitDiscovererAttribute(typeName, assemblyName));658 result.GetConstructorArguments().Returns(new object[] { typeName, assemblyName });659 return result;660 }661 public static IAttributeInfo TraitDiscovererAttribute(Type discovererType)662 {663 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();664 result.Attribute.Returns(new TraitDiscovererAttribute(discovererType));665 result.GetConstructorArguments().Returns(new object[] { discovererType });666 return result;667 }668 public static IAttributeInfo TraitDiscovererAttribute<TDiscoverer>() =>669 TraitDiscovererAttribute(typeof(TDiscoverer));670 public static ITypeInfo TypeInfo(671 string? typeName = null,672 IMethodInfo[]? methods = null,673 IReflectionAttributeInfo[]? attributes = null,674 string? assemblyFileName = null)675 {676 var result = Substitute.For<ITypeInfo, InterfaceProxy<ITypeInfo>>();677 result.Name.Returns(typeName ?? "type:" + Guid.NewGuid().ToString("n"));678 result.GetMethods(false).ReturnsForAnyArgs(methods ?? new IMethodInfo[0]);679 var assemblyInfo = AssemblyInfo(assemblyFileName: assemblyFileName);680 result.Assembly.Returns(assemblyInfo);681 result.GetCustomAttributes("").ReturnsForAnyArgs(callInfo => LookupAttribute(callInfo.Arg<string>(), attributes));682 return result;683 }684 public static XunitTestCase XunitTestCase<TClassUnderTest>(685 string methodName,686 ITestCollection? collection = null,687 object[]? testMethodArguments = null,688 IMessageSink? diagnosticMessageSink = null)689 {690 var method = TestMethod(typeof(TClassUnderTest), methodName, collection);691 return new XunitTestCase(diagnosticMessageSink ?? new NullMessageSink(), TestMethodDisplay.ClassAndMethod, TestMethodDisplayOptions.None, method, testMethodArguments);692 }693 public static XunitTheoryTestCase XunitTheoryTestCase<TClassUnderTest>(694 string methodName,695 ITestCollection? collection = null,696 IMessageSink? diagnosticMessageSink = null)697 {698 var method = TestMethod(typeof(TClassUnderTest), methodName, collection);699 return new XunitTheoryTestCase(diagnosticMessageSink ?? new NullMessageSink(), TestMethodDisplay.ClassAndMethod, TestMethodDisplayOptions.None, method);700 }701 // Helpers702 static Dictionary<string, List<string>> GetTraits(IMethodInfo method)703 {704 var result = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);705 foreach (var traitAttribute in method.GetCustomAttributes(typeof(TraitAttribute)))706 {707 var ctorArgs = traitAttribute.GetConstructorArguments().ToList();708 result.Add((string)ctorArgs[0], (string)ctorArgs[1]);709 }710 return result;711 }712}...
TheoryDiscovererTests.cs
Source:TheoryDiscovererTests.cs
...54 Assert.Equal($"No data found for {typeof(EmptyTheoryDataClass).FullName}.{nameof(EmptyTheoryDataClass.TheoryMethod)}", failure.Messages.Single());55 }56 class EmptyTheoryDataAttribute : DataAttribute57 {58 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod) =>59 new(Array.Empty<ITheoryDataRow>());60 }61 class EmptyTheoryDataClass62 {63 [Theory, EmptyTheoryData]64 public void TheoryMethod(int x) { }65 }66 [Fact]67 public async void DiscoveryOptions_PreEnumerateTheoriesSetToTrue_YieldsTestCasePerDataRow()68 {69 discoveryOptions.SetPreEnumerateTheories(true);70 var discoverer = new TheoryDiscoverer();71 var testMethod = Mocks.TestMethod<MultipleDataClass>(nameof(MultipleDataClass.TheoryMethod));72 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();73 var testCases = (await discoverer.Discover(discoveryOptions, testMethod, factAttribute)).ToList();74 Assert.Collection(75 testCases.Select(tc => tc.TestCaseDisplayName).OrderBy(x => x),76 displayName => Assert.Equal($"{typeof(MultipleDataClass).FullName}.{nameof(MultipleDataClass.TheoryMethod)}(x: 2112)", displayName),77 displayName => Assert.Equal($"{typeof(MultipleDataClass).FullName}.{nameof(MultipleDataClass.TheoryMethod)}(x: 42)", displayName)78 );79 }80 [Fact]81 public async void DiscoveryOptions_PreEnumerateTheoriesSetToFalse_YieldsSingleTestCase()82 {83 discoveryOptions.SetPreEnumerateTheories(false);84 var discoverer = new TheoryDiscoverer();85 var testMethod = Mocks.TestMethod<MultipleDataClass>(nameof(MultipleDataClass.TheoryMethod));86 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();87 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);88 var testCase = Assert.Single(testCases);89 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);90 Assert.Equal($"{typeof(MultipleDataClass).FullName}.{nameof(MultipleDataClass.TheoryMethod)}", testCase.TestCaseDisplayName);91 }92 class MultipleDataAttribute : DataAttribute93 {94 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod) =>95 new(96 new[]97 {98 new TheoryDataRow(42),99 new TheoryDataRow(2112)100 }101 );102 }103 class MultipleDataClass104 {105 [Theory, MultipleDataAttribute]106 public void TheoryMethod(int x) { }107 }108 [Fact]109 public async void DiscoveryOptions_PreEnumerateTheoriesSetToTrueWithSkipOnData_YieldsSkippedTestCasePerDataRow()110 {111 discoveryOptions.SetPreEnumerateTheories(true);112 var discoverer = new TheoryDiscoverer();113 var testMethod = Mocks.TestMethod<MultipleDataClassSkipped>(nameof(MultipleDataClassSkipped.TheoryMethod));114 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();115 var testCases = (await discoverer.Discover(discoveryOptions, testMethod, factAttribute)).ToList();116 Assert.Collection(117 testCases.OrderBy(tc => tc.TestCaseDisplayName),118 testCase =>119 {120 Assert.Equal($"{typeof(MultipleDataClassSkipped).FullName}.{nameof(MultipleDataClassSkipped.TheoryMethod)}(x: 2112)", testCase.TestCaseDisplayName);121 Assert.Equal("Skip this attribute", testCase.SkipReason);122 },123 testCase =>124 {125 Assert.Equal($"{typeof(MultipleDataClassSkipped).FullName}.{nameof(MultipleDataClassSkipped.TheoryMethod)}(x: 42)", testCase.TestCaseDisplayName);126 Assert.Equal("Skip this attribute", testCase.SkipReason);127 }128 );129 }130 class MultipleDataClassSkipped131 {132 [Theory, MultipleData(Skip = "Skip this attribute")]133 public void TheoryMethod(int x) { }134 }135 [Fact]136 public async void ThrowingData()137 {138 var spy = SpyMessageSink.Capture();139 TestContext.Current!.DiagnosticMessageSink = spy;140 var discoverer = new TheoryDiscoverer();141 var testMethod = Mocks.TestMethod<ThrowingDataClass>("TheoryWithMisbehavingData");142 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();143 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);144 var testCase = Assert.Single(testCases);145 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);146 Assert.Equal($"{typeof(ThrowingDataClass).FullName}.{nameof(ThrowingDataClass.TheoryWithMisbehavingData)}", testCase.TestCaseDisplayName);147 var diagnostic = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());148 Assert.StartsWith($"Exception thrown during theory discovery on '{typeof(ThrowingDataClass).FullName}.{nameof(ThrowingDataClass.TheoryWithMisbehavingData)}'; falling back to single test case.{Environment.NewLine}System.DivideByZeroException: Attempted to divide by zero.", diagnostic.Message);149 }150 class ThrowingDataAttribute : DataAttribute151 {152 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo method)153 {154 throw new DivideByZeroException();155 }156 }157 class ThrowingDataClass158 {159 [Theory, ThrowingData]160 public void TheoryWithMisbehavingData(string a) { }161 }162 [Fact]163 public async void DataDiscovererReturningNullYieldsSingleTheoryTestCase()164 {165 var spy = SpyMessageSink.Capture();166 TestContext.Current!.DiagnosticMessageSink = spy;167 var discoverer = new TheoryDiscoverer();168 var theoryAttribute = Mocks.TheoryAttribute();169 var dataAttribute = Mocks.DataAttribute();170 var testMethod = Mocks.TestMethod("MockTheoryType", "MockTheoryMethod", methodAttributes: new[] { theoryAttribute, dataAttribute });171 var testCases = await discoverer.Discover(discoveryOptions, testMethod, theoryAttribute);172 var testCase = Assert.Single(testCases);173 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);174 Assert.Equal("MockTheoryType.MockTheoryMethod", testCase.TestCaseDisplayName);175 var diagnostic = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());176 Assert.StartsWith($"Exception thrown during theory discovery on 'MockTheoryType.MockTheoryMethod'; falling back to single test case.{Environment.NewLine}System.InvalidOperationException: Sequence contains no elements", diagnostic.Message);177 }178 [Fact]179 public async void NonSerializableDataYieldsSingleTheoryTestCase()180 {181 var spy = SpyMessageSink.Capture();182 TestContext.Current!.DiagnosticMessageSink = spy;183 var discoverer = new TheoryDiscoverer();184 var testMethod = Mocks.TestMethod<NonSerializableDataClass>(nameof(NonSerializableDataClass.TheoryMethod));185 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();186 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);187 var testCase = Assert.Single(testCases);188 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);189 Assert.Equal($"{typeof(NonSerializableDataClass).FullName}.{nameof(NonSerializableDataClass.TheoryMethod)}", testCase.TestCaseDisplayName);190 var diagnostic = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());191 Assert.Equal($"Non-serializable data (one or more of: '{typeof(NonSerializableDataAttribute).FullName}') found for '{typeof(NonSerializableDataClass).FullName}.{nameof(NonSerializableDataClass.TheoryMethod)}'; falling back to single test case.", diagnostic.Message);192 }193 class NonSerializableDataAttribute : DataAttribute194 {195 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo method) =>196 new(197 new[]198 {199 new TheoryDataRow(42),200 new TheoryDataRow(new NonSerializableDataAttribute())201 }202 );203 }204 class NonSerializableDataClass205 {206 [Theory, NonSerializableData]207 public void TheoryMethod(object a) { }208 }209 [Fact]210 public async void NoSuchDataDiscoverer_ThrowsInvalidOperationException()211 {212 var results = await RunAsync<_TestFailed>(typeof(NoSuchDataDiscovererClass));213 var failure = Assert.Single(results);214 Assert.Equal(typeof(InvalidOperationException).FullName, failure.ExceptionTypes.Single());215 Assert.Equal($"Data discoverer specified for {typeof(NoSuchDataDiscovererAttribute).FullName} on {typeof(NoSuchDataDiscovererClass).FullName}.{nameof(NoSuchDataDiscovererClass.Test)} does not exist.", failure.Messages.Single());216 }217 class NoSuchDataDiscovererClass218 {219 [Theory]220 [NoSuchDataDiscoverer]221 public void Test() { }222 }223 [DataDiscoverer("Foo.Blah.ThingDiscoverer", "invalid_assembly_name")]224 public class NoSuchDataDiscovererAttribute : DataAttribute225 {226 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod)227 {228 throw new NotImplementedException();229 }230 }231 [Fact]232 public async void NotADataDiscoverer_ThrowsInvalidOperationException()233 {234 var results = await RunAsync<_TestFailed>(typeof(NotADataDiscovererClass));235 var failure = Assert.Single(results);236 Assert.Equal("System.InvalidOperationException", failure.ExceptionTypes.Single());237 Assert.Equal($"Data discoverer specified for {typeof(NotADataDiscovererAttribute).FullName} on {typeof(NotADataDiscovererClass).FullName}.{nameof(NotADataDiscovererClass.Test)} does not implement IDataDiscoverer.", failure.Messages.Single());238 }239 class NotADataDiscovererClass240 {241 [Theory]242 [NotADataDiscoverer]243 public void Test() { }244 }245 [DataDiscoverer(typeof(TheoryDiscovererTests))]246 public class NotADataDiscovererAttribute : DataAttribute247 {248 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod)249 {250 throw new NotImplementedException();251 }252 }253 [Fact]254 public async void DiscoveryDisabledOnTheoryAttribute_YieldsSingleTheoryTestCase()255 {256 var discoverer = new TheoryDiscoverer();257 var testMethod = Mocks.TestMethod<NonDiscoveryOnTheoryAttribute>(nameof(NonDiscoveryOnTheoryAttribute.TheoryMethod));258 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();259 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);260 var testCase = Assert.Single(testCases);261 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);262 Assert.Equal($"{typeof(NonDiscoveryOnTheoryAttribute).FullName}.{nameof(NonDiscoveryOnTheoryAttribute.TheoryMethod)}", testCase.TestCaseDisplayName);...
XunitTestInvokerTests.cs
Source:XunitTestInvokerTests.cs
...232 {233 this.messages = messages;234 this.identifier = identifier;235 }236 public override void After(MethodInfo methodUnderTest, _ITest test)237 {238 messages.Add("After #" + identifier);239 base.After(methodUnderTest, test);240 }241 public override void Before(MethodInfo methodUnderTest, _ITest test)242 {243 messages.Add("Before #" + identifier);244 base.Before(methodUnderTest, test);245 }246 }247 class TestableXunitTestInvoker : XunitTestInvoker248 {249 readonly IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes;250 readonly object?[] constructorArguments;251 readonly Action? lambda;252 readonly IMessageBus messageBus;253 readonly _ITest test;254 readonly Type testClass;255 readonly MethodInfo testMethod;256 readonly object?[]? testMethodArguments;257 public readonly ExceptionAggregator Aggregator;258 public readonly IXunitTestCase TestCase;259 public readonly CancellationTokenSource TokenSource;260 TestableXunitTestInvoker(261 _ITest test,262 IMessageBus messageBus,263 Type testClass,264 object?[] constructorArguments,265 MethodInfo testMethod,266 object?[]? testMethodArguments,267 IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes,268 ExceptionAggregator aggregator,269 CancellationTokenSource cancellationTokenSource,270 Action? lambda)271 {272 this.test = test;273 this.messageBus = messageBus;274 this.testClass = testClass;275 this.constructorArguments = constructorArguments;276 this.testMethod = testMethod;277 this.testMethodArguments = testMethodArguments;278 this.beforeAfterAttributes = beforeAfterAttributes;279 this.lambda = lambda;...
TestMethodTestCaseTests.cs
Source:TestMethodTestCaseTests.cs
...148 {149 var method = TestData.TestMethod<ClassUnderTest>("OpenGeneric");150 var testCase = new TestableTestMethodTestCase(method, new[] { testArg });151 var closedMethod = testCase.Method;152 var methodInfo = Assert.IsAssignableFrom<_IReflectionMethodInfo>(method.Method).MethodInfo;153 Assert.True(methodInfo.IsGenericMethodDefinition);154 var closedMethodInfo = Assert.IsAssignableFrom<_IReflectionMethodInfo>(closedMethod).MethodInfo;155 Assert.False(closedMethodInfo.IsGenericMethodDefinition);156 var genericType = Assert.Single(closedMethodInfo.GetGenericArguments());157 Assert.Same(expectedGenericType, genericType);158 }159 [Fact]160 public void IncompatibleArgumentsSetsInitializationException()161 {162 var method = TestData.TestMethod<ClassUnderTest>("NonGeneric");163 var testCase = new TestableTestMethodTestCase(method, new[] { new ClassUnderTest() });164 Assert.NotNull(testCase.InitializationException);165 Assert.IsType<InvalidOperationException>(testCase.InitializationException);166 Assert.Equal("The arguments for this test method did not match the parameters: [ClassUnderTest { }]", testCase.InitializationException.Message);167 }168 [Serializable]169 class ClassUnderTest170 {...
XunitTestCaseTests.cs
Source:XunitTestCaseTests.cs
...152 var testAssembly = new TestAssembly(new ReflectionAssemblyInfo(classType.Assembly));153 var testCollection = new TestCollection(testAssembly, null, "Trait inheritance tests");154 var @class = new ReflectionTypeInfo(classType);155 var testClass = new TestClass(testCollection, @class);156 var methodInfo = new ReflectionMethodInfo(classType.GetMethod("TraitsTest")!);157 var testMethod = new TestMethod(testClass, methodInfo);158 var testCase = new TestableXunitTestCase(testMethod);159 var testTraits = testCase.Traits["Test"];160 Assert.NotNull(testTraits);161 foreach (var expectedTrait in expectedTraits)162 Assert.Contains(expectedTrait, testTraits);163 }164 class BaseClassWithoutTraits165 { }166 [Trait("Test", "BaseOne")]167 class BaseClassWithSingleTrait168 { }169 [Trait("Test", "BaseOne"), Trait("Test", "BaseTwo")]170 class BaseClassWithMultipleTraits...
Mocks.TestCases.cs
Source:Mocks.TestCases.cs
...108 uniqueID109 );110 public static _ITestClass TestClass(111 string? typeName,112 _IMethodInfo[]? methods = null,113 _IReflectionAttributeInfo[]? attributes = null,114 _ITypeInfo? baseType = null,115 _ITestCollection? collection = null,116 string? uniqueID = null) =>117 TestClass(TypeInfo(typeName, methods, attributes, baseType), collection, uniqueID);118 public static _ITestClass TestClass(119 _ITypeInfo? typeInfo = null,120 _ITestCollection? collection = null,121 string? uniqueID = null)122 {123 typeInfo ??= TypeInfo();124 collection ??= TestCollection();125 uniqueID ??= "class-id";126 var result = Substitute.For<_ITestClass, InterfaceProxy<_ITestClass>>();127 result.Class.Returns(typeInfo);128 result.TestCollection.Returns(collection);129 result.UniqueID.Returns(uniqueID);130 return result;131 }132 public static _ITestCollection TestCollection(133 Assembly assembly,134 _ITypeInfo? definition = null,135 string? displayName = null,136 string? uniqueID = null) =>137 TestCollection(TestAssembly(assembly), definition, displayName, uniqueID);138 public static _ITestCollection TestCollection(139 _ITestAssembly? assembly = null,140 _ITypeInfo? definition = null,141 string? displayName = null,142 string? uniqueID = null)143 {144 assembly ??= TestAssembly();145 displayName ??= "Mock test collection";146 uniqueID ??= "collection-id";147 var result = Substitute.For<_ITestCollection, InterfaceProxy<_ITestCollection>>();148 result.CollectionDefinition.Returns(definition);149 result.DisplayName.Returns(displayName);150 result.TestAssembly.Returns(assembly);151 result.UniqueID.Returns(uniqueID);152 return result;153 }154 public static _ITestMethod TestMethod(155 string? typeName = null,156 string? methodName = null,157 string? displayName = null,158 string? skip = null,159 int timeout = 0,160 _IParameterInfo[]? parameters = null,161 _IReflectionAttributeInfo[]? classAttributes = null,162 _IReflectionAttributeInfo[]? methodAttributes = null,163 _ITestCollection? collection = null,164 string? uniqueID = null)165 {166 parameters ??= EmptyParameterInfos;167 classAttributes ??= EmptyAttributeInfos;168 methodAttributes ??= EmptyAttributeInfos;169 // Ensure that there's a FactAttribute, or else it's not technically a test method170 var factAttribute = methodAttributes.FirstOrDefault(attr => typeof(FactAttribute).IsAssignableFrom(attr.Attribute.GetType()));171 if (factAttribute == null)172 {173 factAttribute = FactAttribute(displayName, skip, timeout);174 methodAttributes = methodAttributes.Concat(new[] { factAttribute }).ToArray();175 }176 var testClass = TestClass(typeName, attributes: classAttributes, collection: collection);177 var methodInfo = MethodInfo(methodName, methodAttributes, parameters, testClass.Class);178 return TestMethod(methodInfo, testClass, uniqueID);179 }180 public static _ITestMethod TestMethod<TClassUnderTest>(181 string methodName,182 _ITestCollection? collection = null,183 string? uniqueID = null) =>184 TestMethod(MethodInfo<TClassUnderTest>(methodName), TestClass<TClassUnderTest>(collection), uniqueID);185 public static _ITestMethod TestMethod(186 _IMethodInfo methodInfo,187 _ITestClass testClass,188 string? uniqueID = null)189 {190 uniqueID ??= "method-id";191 var result = Substitute.For<_ITestMethod, InterfaceProxy<_ITestMethod>>();192 result.Method.Returns(methodInfo);193 result.TestClass.Returns(testClass);194 result.UniqueID.Returns(uniqueID);195 return result;196 }197 }198}...
Mocks.Reflection.cs
Source:Mocks.Reflection.cs
...27 return result;28 }29 public static _IReflectionAssemblyInfo AssemblyInfo(Assembly assembly) =>30 Reflector.Wrap(assembly);31 static IReadOnlyDictionary<string, IReadOnlyList<string>> GetTraits(_IMethodInfo method)32 {33 var result = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);34 foreach (var traitAttribute in method.GetCustomAttributes(typeof(TraitAttribute)))35 {36 var ctorArgs = traitAttribute.GetConstructorArguments().ToList();37 result.Add((string)ctorArgs[0]!, (string)ctorArgs[1]!);38 }39 return result.ToReadOnly();40 }41 public static _IReflectionMethodInfo MethodInfo<TClass>(string methodName) =>42 Guard.ArgumentNotNull(43 $"Could not find method '{methodName}' on '{typeof(TClass).FullName}'",44 Reflector.Wrap(typeof(TClass).GetMethod(methodName)),45 nameof(methodName)46 );47 public static _IMethodInfo MethodInfo(48 string? methodName = null,49 _IReflectionAttributeInfo[]? attributes = null,50 _IParameterInfo[]? parameters = null,51 _ITypeInfo? type = null,52 _ITypeInfo? returnType = null,53 _ITypeInfo[]? genericArguments = null,54 bool isAbstract = false,55 bool isGenericMethodDefinition = false,56 bool isPublic = true,57 bool isStatic = false)58 {59 methodName ??= $"method_{Guid.NewGuid():n}";60 attributes ??= EmptyAttributeInfos;61 parameters ??= EmptyParameterInfos;62 genericArguments ??= EmptyTypeInfos;63 var result = Substitute.For<_IMethodInfo, InterfaceProxy<_IMethodInfo>>();64 result.IsAbstract.Returns(isAbstract);65 result.IsGenericMethodDefinition.Returns(isGenericMethodDefinition);66 result.IsPublic.Returns(isPublic);67 result.IsStatic.Returns(isStatic);68 result.Name.Returns(methodName);69 result.ReturnType.Returns(returnType);70 result.Type.Returns(type);71 result.GetCustomAttributes("").ReturnsForAnyArgs(callInfo => LookupAttribute(callInfo.Arg<string>(), attributes));72 result.GetGenericArguments().Returns(genericArguments);73 result.GetParameters().Returns(parameters);74 // Difficult to simulate MakeGenericMethod here, so better to throw then just return null75 // and if any tests need this, then can override the substitution.76 result.MakeGenericMethod().WhenForAnyArgs(_ => throw new NotImplementedException());77 return result;78 }79 public static _IParameterInfo ParameterInfo(80 string name,81 _ITypeInfo? parameterType = null)82 {83 parameterType ??= TypeObject;84 var result = Substitute.For<_IParameterInfo, InterfaceProxy<_IParameterInfo>>();85 result.Name.Returns(name);86 result.ParameterType.Returns(parameterType);87 return result;88 }89 public static _IReflectionTypeInfo TypeInfo<TClass>() =>90 Reflector.Wrap(typeof(TClass));91 public static _ITypeInfo TypeInfo(92 string? name = null,93 _IMethodInfo[]? methods = null,94 _IReflectionAttributeInfo[]? attributes = null,95 _ITypeInfo? baseType = null,96 _ITypeInfo[]? interfaces = null,97 bool isAbstract = false,98 bool isGenericParameter = false,99 bool isGenericType = false,100 bool isValueType = false,101 _ITypeInfo[]? genericArguments = null,102 string? assemblyFileName = null)103 {104 baseType ??= TypeObject;105 name ??= $"type_{Guid.NewGuid():n}";106 methods ??= EmptyMethodInfos;107 interfaces ??= EmptyTypeInfos;108 genericArguments ??= EmptyTypeInfos;109 var assemblyInfo = AssemblyInfo(assemblyFileName: assemblyFileName);110 var result = Substitute.For<_ITypeInfo, InterfaceProxy<_ITypeInfo>>();111 result.Assembly.Returns(assemblyInfo);112 result.BaseType.Returns(baseType);113 result.IsAbstract.Returns(isAbstract);114 result.IsGenericParameter.Returns(isGenericParameter);115 result.IsGenericType.Returns(isGenericType);116 result.IsValueType.Returns(isValueType);117 result.Name.Returns(name);118 result.GetCustomAttributes("").ReturnsForAnyArgs(callInfo => LookupAttribute(callInfo.Arg<string>(), attributes));119 result.GetGenericArguments().Returns(genericArguments);120 result.GetMethod("", false).ReturnsForAnyArgs(callInfo => methods.FirstOrDefault(m => m.Name == callInfo.Arg<string>()));...
ReflectionAbstractionExtensionsTests.cs
Source:ReflectionAbstractionExtensionsTests.cs
...4{5 public class ToRuntimeMethod6 {7 [Fact]8 public static void WhenUsingReflectionMethodInfo_ReturnsExistingMethodInfo()9 {10 var methodInfo = Mocks.MethodInfo<ToRuntimeMethod>("WhenUsingReflectionMethodInfo_ReturnsExistingMethodInfo");11 var result = methodInfo.ToRuntimeMethod();12 Assert.NotNull(result);13 Assert.Same(methodInfo.MethodInfo, result);14 }15 [Fact]16 public static void WhenUsingNonReflectionMethodInfo_MethodExists_ReturnsMethodInfo()17 {18#if BUILD_X8619 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeMethod", assemblyFileName: "xunit.v3.core.tests.x86.exe");20#else21 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeMethod", assemblyFileName: "xunit.v3.core.tests.exe");22#endif23 var methodInfo = Mocks.MethodInfo("WhenUsingNonReflectionMethodInfo_MethodExists_ReturnsMethodInfo", isStatic: true, type: typeInfo);24 var result = methodInfo.ToRuntimeMethod();25 Assert.NotNull(result);26 Assert.Same(typeof(ToRuntimeMethod).GetMethod("WhenUsingNonReflectionMethodInfo_MethodExists_ReturnsMethodInfo"), result);27 }28 [Fact]29 public static void WhenUsingNonReflectionMethodInfo_MethodDoesNotExist_ReturnsNull()30 {31 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeMethod", assemblyFileName: "xunit.v3.core.tests.exe");32 var methodInfo = Mocks.MethodInfo("UnknownMethod", isStatic: true, type: typeInfo);33 var result = methodInfo.ToRuntimeMethod();34 Assert.Null(result);35 }36 }37 public class ToRuntimeType38 {39 [Fact]40 public static void WhenUsingReflectionTypeInfo_ReturnsExistingType()41 {42 var typeInfo = Mocks.TypeInfo<ToRuntimeType>();43 var result = typeInfo.ToRuntimeType();44 Assert.NotNull(result);45 Assert.Same(typeInfo.Type, result);46 }...
MethodInfo
Using AI Code Generation
1using Xunit.v3;2{3 {4 public static MethodInfo Method([CallerMemberName] string methodName = null)5 {6 var stack = new StackTrace();7 var type = stack.GetFrame(1).GetMethod().DeclaringType;8 return type.GetMethod(methodName);9 }10 }11}12using Xunit.v3;13using Xunit;14{15 public void TestMethod1()16 {17 var method = Mocks.Method();18 Assert.Equal("TestMethod1", method.Name);19 }20}
MethodInfo
Using AI Code Generation
1using Xunit.v3;2using Xunit.v3.Mocks;3using Xunit.v3.Mocks.MethodInfo;4using Xunit.v3.Mocks.XunitTestCase;5using Xunit.v3.Mocks.XunitTestCaseRunner;6using Xunit.v3.Mocks.XunitTestRunner;7using Xunit.v3.Mocks.XunitTestRunnerFactory;8using Xunit.v3.Mocks.XunitTestRunnerFactoryFactory;9using Xunit.v3.Mocks.XunitTestRunnerFactoryFactoryRunner;10using Xunit.v3.Mocks.XunitTestRunnerFactoryRunner;11using Xunit.v3.Mocks.XunitTestRunnerRunner;12using Xunit.v3.Mocks.XunitTestRunnerRunnerRunner;13using Xunit.v3.Mocks.XunitTestRunnerRunnerRunnerRunner;14using Xunit.v3.Mocks.XunitTestRunnerRunnerRunnerRunnerRunner;15using Xunit.v3.Mocks.XunitTestRunnerRunnerRunnerRunnerRunnerRunner;16using Xunit.v3.Mocks.XunitTestRunnerRunnerRunnerRunnerRunnerRunnerRunner;17using Xunit.v3.Mocks.XunitTestRunnerRunnerRunnerRunnerRunnerRunnerRunnerRunner;18using Xunit.v3.Mocks.XunitTestRunnerRunnerRunnerRunnerRunnerRunnerRunnerRunnerRunner;
MethodInfo
Using AI Code Generation
1using Xunit;2using Xunit.v3.Mocks;3{4 public void TestMethod()5 {6 var methodInfo = Xunit.v3.Mocks.MethodInfo("TestMethod");7 var testMethodClassInstance = Xunit.v3.Mocks.CreateInstance(methodInfo.DeclaringType);8 methodInfo.Invoke(testMethodClassInstance, new object[0]);9 var result = Xunit.v3.Mocks.GetResult(methodInfo);10 Xunit.v3.Mocks.AssertResult(methodInfo, "expected result");11 }12}13using Xunit;14using Xunit.v3.Mocks;15{16 public void TestMethod()17 {18 var testMethodClassInstance = Xunit.v3.Mocks.CreateInstance(typeof(TestClass));19 Xunit.v3.Mocks.Invoke(testMethodClassInstance, "TestMethod");20 var result = Xunit.v3.Mocks.GetResult(typeof(TestClass), "TestMethod");21 Xunit.v3.Mocks.AssertResult(typeof(TestClass), "TestMethod", "expected result");22 }23}
MethodInfo
Using AI Code Generation
1using Xunit;2using Xunit.v3;3{4 {5 public void TestMethod1()6 {7 MethodInfo methodInfo = Xunit.v3.Mocks.MethodInfo(8 typeof(UnitTest1),9 nameof(TestMethod1));10 object[] parameters = new object[0];11 object result = methodInfo.Invoke(null, parameters);12 Xunit.v3.Mocks.Assert(result);13 }14 }15}16using Xunit;17using Xunit.v3;18{19 {20 public void TestMethod1()21 {22 MethodInfo methodInfo = Xunit.v3.Mocks.MethodInfo(23 typeof(UnitTest1),24 nameof(TestMethod1));25 object[] parameters = new object[0];26 object result = methodInfo.Invoke(null, parameters);27 Xunit.v3.Mocks.Assert(result);28 }29 }30}
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!!