How to use TestCase method of Xunit.v3.Mocks class

Best Xunit code snippet using Xunit.v3.Mocks.TestCase

Mocks.cs

Source:Mocks.cs Github

copy

Full Screen

...107 dataAttribute.GetData(null!).ReturnsForAnyArgs(data);108 result.Attribute.Returns(dataAttribute);109 return result;110 }111 public static ExecutionErrorTestCase ExecutionErrorTestCase(112 string message,113 IMessageSink? diagnosticMessageSink = null)114 {115 var testMethod = TestMethod();116 return new ExecutionErrorTestCase(117 diagnosticMessageSink ?? new NullMessageSink(),118 TestMethodDisplay.ClassAndMethod,119 TestMethodDisplayOptions.None,120 testMethod,121 message122 );123 }124 public static IReflectionAttributeInfo FactAttribute(125 string? displayName = null,126 string? skip = null,127 int timeout = 0)128 {129 var result = Substitute.For<IReflectionAttributeInfo, InterfaceProxy<IReflectionAttributeInfo>>();130 result.Attribute.Returns(new FactAttribute { DisplayName = displayName, Skip = skip, Timeout = timeout });131 result.GetNamedArgument<string>("DisplayName").Returns(displayName);132 result.GetNamedArgument<string>("Skip").Returns(skip);133 result.GetNamedArgument<int>("Timeout").Returns(timeout);134 return result;135 }136 static IEnumerable<IAttributeInfo> LookupAttribute(137 string fullyQualifiedTypeName,138 IReflectionAttributeInfo[]? attributes)139 {140 if (attributes == null)141 return Enumerable.Empty<IAttributeInfo>();142 var attributeType = Type.GetType(fullyQualifiedTypeName);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}...

Full Screen

Full Screen

TheoryDiscovererTests.cs

Source:TheoryDiscovererTests.cs Github

copy

Full Screen

...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);263 }264 class NonDiscoveryOnTheoryAttribute265 {266 public static IEnumerable<object[]> foo { get { return Enumerable.Empty<object[]>(); } }267 public static IEnumerable<object[]> bar { get { return Enumerable.Empty<object[]>(); } }268 [Theory(DisableDiscoveryEnumeration = true)]269 [MemberData(nameof(foo))]270 [MemberData(nameof(bar))]271 public static void TheoryMethod(int x) { }272 }273 [Fact]274 public async void DiscoveryDisabledOnMemberData_YieldsSingleTheoryTestCase()275 {276 var discoverer = new TheoryDiscoverer();277 var testMethod = Mocks.TestMethod<NonDiscoveryEnumeratedData>(nameof(NonDiscoveryEnumeratedData.TheoryMethod));278 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();279 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);280 var testCase = Assert.Single(testCases);281 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);282 Assert.Equal($"{typeof(NonDiscoveryEnumeratedData).FullName}.{nameof(NonDiscoveryEnumeratedData.TheoryMethod)}", testCase.TestCaseDisplayName);283 }284 class NonDiscoveryEnumeratedData285 {286 public static IEnumerable<object[]> foo { get { return Enumerable.Empty<object[]>(); } }287 public static IEnumerable<object[]> bar { get { return Enumerable.Empty<object[]>(); } }288 [Theory]289 [MemberData(nameof(foo), DisableDiscoveryEnumeration = true)]290 [MemberData(nameof(bar), DisableDiscoveryEnumeration = true)]291 public static void TheoryMethod(int x) { }292 }293 [Fact]294 public async void MixedDiscoveryEnumerationOnMemberData_YieldsSingleTheoryTestCase()295 {296 var discoverer = new TheoryDiscoverer();297 var testMethod = Mocks.TestMethod<MixedDiscoveryEnumeratedData>(nameof(MixedDiscoveryEnumeratedData.TheoryMethod));298 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();299 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);300 var testCase = Assert.Single(testCases);301 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);302 Assert.Equal($"{typeof(MixedDiscoveryEnumeratedData).FullName}.{nameof(MixedDiscoveryEnumeratedData.TheoryMethod)}", testCase.TestCaseDisplayName);303 }304 class MixedDiscoveryEnumeratedData305 {306 public static IEnumerable<object[]> foo { get { return Enumerable.Empty<object[]>(); } }307 public static IEnumerable<object[]> bar { get { return Enumerable.Empty<object[]>(); } }308 [Theory]309 [MemberData(nameof(foo), DisableDiscoveryEnumeration = false)]310 [MemberData(nameof(bar), DisableDiscoveryEnumeration = true)]311 public static void TheoryMethod(int x) { }312 }313 [Fact]314 public async void SkippedTheoryWithNoData()315 {316 var msgs = await RunAsync(typeof(SkippedWithNoData));317 var skip = Assert.Single(msgs.OfType<_TestSkipped>());318 var skipStarting = Assert.Single(msgs.OfType<_TestStarting>().Where(s => s.TestUniqueID == skip.TestUniqueID));319 Assert.Equal($"{typeof(SkippedWithNoData).FullName}.{nameof(SkippedWithNoData.TestMethod)}", skipStarting.TestDisplayName);320 Assert.Equal("I have no data", skip.Reason);321 }322 class SkippedWithNoData323 {324 [Theory(Skip = "I have no data")]325 public void TestMethod(int value) { }326 }327 [Fact]328 public async void SkippedTheoryWithData()329 {330 var msgs = await RunAsync(typeof(SkippedWithData));331 var skip = Assert.Single(msgs.OfType<_TestSkipped>());332 var skipStarting = Assert.Single(msgs.OfType<_TestStarting>().Where(s => s.TestUniqueID == skip.TestUniqueID));333 Assert.Equal($"{typeof(SkippedWithData).FullName}.{nameof(SkippedWithData.TestMethod)}", skipStarting.TestDisplayName);334 Assert.Equal("I have data", skip.Reason);335 }336 class SkippedWithData337 {338 [Theory(Skip = "I have data")]339 [InlineData(42)]340 [InlineData(2112)]341 public void TestMethod(int value) { }342 }343 [Fact]344 public async void TheoryWithSerializableInputDataThatIsntSerializableAfterConversion_YieldsSingleTheoryTestCase()345 {346 TestContext.Current!.DiagnosticMessageSink = SpyMessageSink.Capture();347 var discoverer = new TheoryDiscoverer();348 var testMethod = Mocks.TestMethod<ClassWithExplicitConvertedData>(nameof(ClassWithExplicitConvertedData.ParameterDeclaredExplicitConversion));349 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();350 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);351 var testCase = Assert.Single(testCases);352 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);353 Assert.Equal($"{typeof(ClassWithExplicitConvertedData).FullName}.{nameof(ClassWithExplicitConvertedData.ParameterDeclaredExplicitConversion)}", testCase.TestCaseDisplayName);354 }355 class ClassWithExplicitConvertedData356 {357 // Explicit conversion defined on the parameter's type358 [Theory]359 [InlineData("abc")]360 public void ParameterDeclaredExplicitConversion(Explicit e)361 {362 Assert.Equal("abc", e.Value);363 }364 public class Explicit365 {366 public string? Value { get; set; }367 public static explicit operator Explicit(string value)368 {369 return new Explicit() { Value = value };370 }371 public static explicit operator string?(Explicit e)372 {373 return e.Value;374 }375 }376 }377 class ClassWithSkippedTheoryDataRows378 {379 public static IEnumerable<ITheoryDataRow> Data =>380 new[]381 {382 new TheoryDataRow(42) { Skip = "Do not run this test" },383 new TheoryDataRow(2112),384 };385 [Theory]386 [MemberData(nameof(Data))]387 public void TestWithSomeSkippedTheoryRows(int x)388 {389 Assert.Equal(96, x);390 }391 }392 [Fact]393 public async void CanSkipFromTheoryDataRow_Preenumerated()394 {395 var discoverer = new TheoryDiscoverer();396 var testMethod = Mocks.TestMethod<ClassWithSkippedTheoryDataRows>(nameof(ClassWithSkippedTheoryDataRows.TestWithSomeSkippedTheoryRows));397 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();398 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);399 Assert.Collection(400 testCases.OrderBy(tc => tc.TestCaseDisplayName),401 testCase =>402 {403 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);404 Assert.Equal($"{typeof(ClassWithSkippedTheoryDataRows).FullName}.{nameof(ClassWithSkippedTheoryDataRows.TestWithSomeSkippedTheoryRows)}(x: 2112)", testCase.TestCaseDisplayName);405 Assert.Null(testCase.SkipReason);406 },407 testCase =>408 {409 Assert.IsType<XunitSkippedDataRowTestCase>(testCase);410 Assert.Equal($"{typeof(ClassWithSkippedTheoryDataRows).FullName}.{nameof(ClassWithSkippedTheoryDataRows.TestWithSomeSkippedTheoryRows)}(x: 42)", testCase.TestCaseDisplayName);411 Assert.Equal("Do not run this test", testCase.SkipReason);412 }413 );414 }415 [Trait("Class", "ClassWithTraitsOnTheoryDataRows")]416 class ClassWithTraitsOnTheoryDataRows417 {418 public static IEnumerable<ITheoryDataRow> Data =>419 new[]420 {421 new TheoryDataRow(42).WithTrait("Number", "42"),422 new TheoryDataRow(2112) { Skip = "I am skipped" }.WithTrait("Number", "2112"),423 };424 [Theory]425 [Trait("Theory", "TestWithTraits")]426 [MemberData(nameof(Data))]427 public void TestWithTraits(int x)428 {429 Assert.Equal(96, x);430 }431 }432 [Fact]433 public async void CanAddTraitsFromTheoryDataRow_Preenumerated()434 {435 var discoverer = new TheoryDiscoverer();436 var testMethod = Mocks.TestMethod<ClassWithTraitsOnTheoryDataRows>(nameof(ClassWithTraitsOnTheoryDataRows.TestWithTraits));437 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();438 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);439 Assert.Collection(440 testCases.OrderBy(tc => tc.TestCaseDisplayName),441 testCase =>442 {443 Assert.IsType<XunitSkippedDataRowTestCase>(testCase);444 Assert.Equal($"{typeof(ClassWithTraitsOnTheoryDataRows).FullName}.{nameof(ClassWithTraitsOnTheoryDataRows.TestWithTraits)}(x: 2112)", testCase.TestCaseDisplayName);445 Assert.Collection(446 testCase.Traits.OrderBy(kvp => kvp.Key),447 kvp => // Assembly level trait448 {449 Assert.Equal("Assembly", kvp.Key);450 var traitValue = Assert.Single(kvp.Value);451 Assert.Equal("Trait", traitValue);452 },453 kvp => // Class level trait454 {455 Assert.Equal("Class", kvp.Key);456 var traitValue = Assert.Single(kvp.Value);457 Assert.Equal("ClassWithTraitsOnTheoryDataRows", traitValue);458 },459 kvp => // Row level trait460 {461 Assert.Equal("Number", kvp.Key);462 var traitValue = Assert.Single(kvp.Value);463 Assert.Equal("2112", traitValue);464 },465 kvp => // Theory level trait466 {467 Assert.Equal("Theory", kvp.Key);468 var traitValue = Assert.Single(kvp.Value);469 Assert.Equal("TestWithTraits", traitValue);470 }471 );472 },473 testCase =>474 {475 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);476 Assert.Equal($"{typeof(ClassWithTraitsOnTheoryDataRows).FullName}.{nameof(ClassWithTraitsOnTheoryDataRows.TestWithTraits)}(x: 42)", testCase.TestCaseDisplayName);477 Assert.Collection(478 testCase.Traits.OrderBy(kvp => kvp.Key),479 kvp => // Assembly level trait480 {481 Assert.Equal("Assembly", kvp.Key);482 var traitValue = Assert.Single(kvp.Value);483 Assert.Equal("Trait", traitValue);484 },485 kvp => // Class level trait486 {487 Assert.Equal("Class", kvp.Key);488 var traitValue = Assert.Single(kvp.Value);489 Assert.Equal("ClassWithTraitsOnTheoryDataRows", traitValue);490 },491 kvp => // Row level trait492 {493 Assert.Equal("Number", kvp.Key);494 var traitValue = Assert.Single(kvp.Value);495 Assert.Equal("42", traitValue);496 },497 kvp => // Theory level trait498 {499 Assert.Equal("Theory", kvp.Key);500 var traitValue = Assert.Single(kvp.Value);501 Assert.Equal("TestWithTraits", traitValue);502 }503 );504 }505 );506 }507 class ClassWithDisplayNameOnTheoryDataRows508 {509 public static IEnumerable<ITheoryDataRow> Data =>510 new[]511 {512 new TheoryDataRow(42) { TestDisplayName = "I am a special test" },513 new TheoryDataRow(2112),514 new TheoryDataRow(2600) { Skip = "I am skipped", TestDisplayName = "I am a skipped test" }515 };516 [Theory]517 [MemberData(nameof(Data))]518 public void TestWithDisplayName(int x)519 {520 Assert.Equal(96, x);521 }522 }523 [Fact]524 public async void CanSetDisplayNameFromTheoryDataRow_Preenumerated()525 {526 var discoverer = new TheoryDiscoverer();527 var testMethod = Mocks.TestMethod<ClassWithDisplayNameOnTheoryDataRows>(nameof(ClassWithDisplayNameOnTheoryDataRows.TestWithDisplayName));528 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();529 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);530 Assert.Collection(531 testCases.OrderBy(tc => tc.TestCaseDisplayName),532 testCase =>533 {534 Assert.IsType<XunitSkippedDataRowTestCase>(testCase);535 Assert.Equal("I am a skipped test(x: 2600)", testCase.TestCaseDisplayName);536 },537 testCase =>538 {539 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);540 Assert.Equal("I am a special test(x: 42)", testCase.TestCaseDisplayName);541 },542 testCase =>543 {544 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);545 Assert.Equal($"{typeof(ClassWithDisplayNameOnTheoryDataRows).FullName}.{nameof(ClassWithDisplayNameOnTheoryDataRows.TestWithDisplayName)}(x: 2112)", testCase.TestCaseDisplayName);546 }547 );548 }549}...

Full Screen

Full Screen

XunitTestFrameworkDiscovererTests.cs

Source:XunitTestFrameworkDiscovererTests.cs Github

copy

Full Screen

...81 await discoverer.FindTestsForType(testClass);82 typeInfo.Received(1).GetMethods(includePrivateMethods: true);83 }84 [Fact]85 public static async ValueTask TestMethodWithTooManyFactAttributes_ReturnsExecutionErrorTestCase()86 {87 var testClass = Mocks.TestClass<ClassWithTooManyFactAttributesOnTestMethod>();88 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();89 await discoverer.FindTestsForType(testClass);90 var testCase = Assert.Single(discoverer.FindTestsForType_TestCases);91 var errorTestCase = Assert.IsType<ExecutionErrorTestCase>(testCase);92 Assert.Equal($"Test method '{typeof(ClassWithTooManyFactAttributesOnTestMethod).FullName}.{nameof(ClassWithTooManyFactAttributesOnTestMethod.TestMethod)}' has multiple [Fact]-derived attributes", errorTestCase.ErrorMessage);93 }94 class ClassWithTooManyFactAttributesOnTestMethod95 {96 [Fact]97 [Theory]98 public void TestMethod() { }99 }100 [Fact]101 public static async ValueTask DoesNotDiscoverNonFactDecoratedTestMethod()102 {103 var testClass = Mocks.TestClass<ClassWithNoTests>();104 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();105 await discoverer.FindTestsForType(testClass);106 Assert.Empty(discoverer.FindTestsForType_TestCases);107 }108 class ClassWithNoTests109 {110 public void TestMethod() { }111 }112 [Fact]113 public static async ValueTask DiscoversFactDecoratedTestMethod()114 {115 var testClass = Mocks.TestClass<ClassWithOneTest>();116 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();117 await discoverer.FindTestsForType(testClass);118 var testCase = Assert.Single(discoverer.FindTestsForType_TestCases);119 Assert.IsType<XunitTestCase>(testCase);120 Assert.Equal($"{typeof(ClassWithOneTest).FullName}.{nameof(ClassWithOneTest.TestMethod)}", testCase.TestCaseDisplayName);121 }122 class ClassWithOneTest123 {124 [Fact]125 public void TestMethod() { }126 }127 [Fact]128 public static async void Theory_WithPreEnumeration_ReturnsOneTestCasePerDataRecord()129 {130 var testClass = Mocks.TestClass<TheoryWithInlineData>();131 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();132 var discoveryOptions = _TestFrameworkOptions.ForDiscovery(preEnumerateTheories: true);133 await discoverer.FindTestsForType(testClass, discoveryOptions);134 Assert.Collection(135 discoverer.FindTestsForType_TestCases.Select(t => t.TestCaseDisplayName).OrderBy(x => x),136 displayName => Assert.Equal($"{typeof(TheoryWithInlineData).FullName}.{nameof(TheoryWithInlineData.TheoryMethod)}(value: \"Hello world\")", displayName),137 displayName => Assert.Equal($"{typeof(TheoryWithInlineData).FullName}.{nameof(TheoryWithInlineData.TheoryMethod)}(value: 42)", displayName)138 );139 }140 [Fact]141 public static async void Theory_WithoutPreEnumeration_ReturnsOneTestCase()142 {143 var testClass = Mocks.TestClass<TheoryWithInlineData>();144 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();145 var discoveryOptions = _TestFrameworkOptions.ForDiscovery(preEnumerateTheories: false);146 await discoverer.FindTestsForType(testClass, discoveryOptions);147 var testCase = Assert.Single(discoverer.FindTestsForType_TestCases);148 Assert.Equal($"{typeof(TheoryWithInlineData).FullName}.{nameof(TheoryWithInlineData.TheoryMethod)}", testCase.TestCaseDisplayName);149 }150 class TheoryWithInlineData151 {152 [Theory]153 [InlineData("Hello world")]154 [InlineData(42)]155 public static void TheoryMethod(object value) { }156 }157 [Fact]158 public static async void AssemblyWithMultiLevelHierarchyWithFactOverridenInNonImmediateDerivedClass_ReturnsOneTestCase()159 {160 var testClass = Mocks.TestClass<Child>();161 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();162 await discoverer.FindTestsForType(testClass);163 var testCase = Assert.Single(discoverer.FindTestsForType_TestCases);164 Assert.Equal($"{typeof(Child).FullName}.{nameof(GrandParent.FactOverridenInNonImmediateDerivedClass)}", testCase.TestCaseDisplayName);165 }166 public abstract class GrandParent167 {168 [Fact]169 public virtual void FactOverridenInNonImmediateDerivedClass()170 {171 Assert.True(true);172 }173 }174 public abstract class Parent : GrandParent { }175 public class Child : Parent176 {177 public override void FactOverridenInNonImmediateDerivedClass()178 {179 base.FactOverridenInNonImmediateDerivedClass();180 Assert.False(false);181 }182 }183 }184 public static class TestCollectionFactory185 {186 [Fact]187 public static void DefaultTestCollectionFactory()188 {189 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();190 Assert.IsType<CollectionPerClassTestCollectionFactory>(discoverer.TestCollectionFactory);191 }192 [Theory(DisableDiscoveryEnumeration = true)]193 [InlineData(CollectionBehavior.CollectionPerAssembly, typeof(CollectionPerAssemblyTestCollectionFactory))]194 [InlineData(CollectionBehavior.CollectionPerClass, typeof(CollectionPerClassTestCollectionFactory))]195 public static void AssemblyAttributeOverride(196 CollectionBehavior behavior,197 Type expectedFactoryType)198 {199 var behaviorAttribute = Mocks.CollectionBehaviorAttribute(behavior);200 var assembly = Mocks.AssemblyInfo(attributes: new[] { behaviorAttribute });201 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(assembly);202 Assert.IsType(expectedFactoryType, discoverer.TestCollectionFactory);203 }204 [Fact]205 public static void ValidCustomFactory()206 {207 var behaviorAttribute = Mocks.CollectionBehaviorAttribute<CustomTestCollectionFactory>();208 var assembly = Mocks.AssemblyInfo(attributes: new[] { behaviorAttribute });209 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(assembly);210 Assert.IsType<CustomTestCollectionFactory>(discoverer.TestCollectionFactory);211 }212 [Fact]213 public static void InvalidCustomFactoryFallsBackToDefault()214 {215 var spyMessageSink = SpyMessageSink.Capture();216 TestContext.Current!.DiagnosticMessageSink = spyMessageSink;217 var behaviorAttribute = Mocks.CollectionBehaviorAttribute<object>();218 var assembly = Mocks.AssemblyInfo(attributes: new[] { behaviorAttribute });219 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(assembly);220 Assert.IsType<CollectionPerClassTestCollectionFactory>(discoverer.TestCollectionFactory);221 var message = Assert.Single(spyMessageSink.Messages);222 var diagMessage = Assert.IsType<_DiagnosticMessage>(message);223 Assert.Equal("Test collection factory type 'System.Object' does not implement IXunitTestCollectionFactory", diagMessage.Message);224 }225 }226 public static class TestFrameworkDisplayName227 {228 [Fact]229 public static void Defaults()230 {231 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();232 Assert.Matches(@"xUnit.net v3 \d+\.\d+\.\d+(-pre\.\d+(-dev)?(\+[0-9a-f]+)?)? \[collection-per-class, parallel\]", discoverer.TestFrameworkDisplayName);233 }234 [Fact]235 public static void CollectionPerAssembly()236 {237 var behaviorAttribute = Mocks.CollectionBehaviorAttribute(CollectionBehavior.CollectionPerAssembly);238 var assembly = Mocks.AssemblyInfo(attributes: new[] { behaviorAttribute });239 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(assembly);240 Assert.Matches(@"xUnit.net v3 \d+\.\d+\.\d+(-pre\.\d+(-dev)?(\+[0-9a-f]+)?)? \[collection-per-assembly, parallel\]", discoverer.TestFrameworkDisplayName);241 }242 [Fact]243 public static void CustomCollectionFactory()244 {245 var behaviorAttribute = Mocks.CollectionBehaviorAttribute<CustomTestCollectionFactory>();246 var assembly = Mocks.AssemblyInfo(attributes: new[] { behaviorAttribute });247 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(assembly);248 Assert.Matches(@"xUnit.net v3 \d+\.\d+\.\d+(-pre\.\d+(-dev)?(\+[0-9a-f]+)?)? \[my-custom-test-collection-factory, parallel\]", discoverer.TestFrameworkDisplayName);249 }250 [Fact]251 public static void NonParallel()252 {253 var behaviorAttribute = Mocks.CollectionBehaviorAttribute(disableTestParallelization: true);254 var assembly = Mocks.AssemblyInfo(attributes: new[] { behaviorAttribute });255 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(assembly);256 Assert.Matches(@"xUnit.net v3 \d+\.\d+\.\d+(-pre\.\d+(-dev)?(\+[0-9a-f]+)?)? \[collection-per-class, non-parallel\]", discoverer.TestFrameworkDisplayName);257 }258 }259 class ClassWithSingleTest260 {261 [Fact]262 public static void TestMethod() { }263 }264 class CustomTestCollectionFactory : IXunitTestCollectionFactory265 {266 public CustomTestCollectionFactory(_ITestAssembly testAssembly)267 { }268 public string DisplayName => "my-custom-test-collection-factory";269 public _ITestCollection Get(_ITypeInfo testClass) => throw new NotImplementedException();270 }271 class TestableXunitTestFrameworkDiscoverer : XunitTestFrameworkDiscoverer272 {273 public List<_ITestCaseMetadata> FindTestsForType_TestCases = new();274 TestableXunitTestFrameworkDiscoverer(275 _IAssemblyInfo assemblyInfo,276 IXunitTestCollectionFactory? collectionFactory)277 : base(assemblyInfo, configFileName: null, collectionFactory)278 {279 TestAssembly = Mocks.TestAssembly(assemblyInfo.AssemblyPath, uniqueID: "asm-id");280 }281 public new _IAssemblyInfo AssemblyInfo => base.AssemblyInfo;282 public override _ITestAssembly TestAssembly { get; }283 public new ValueTask<_ITestClass> CreateTestClass(_ITypeInfo @class) =>284 base.CreateTestClass(@class);285 public ValueTask<bool> FindTestsForType(286 _ITestClass testClass,287 _ITestFrameworkDiscoveryOptions? discoveryOptions = null) =>288 base.FindTestsForType(289 testClass,290 discoveryOptions ?? _TestFrameworkOptions.ForDiscovery(preEnumerateTheories: true),291 testCase =>292 {293 FindTestsForType_TestCases.Add(testCase);294 return new(true);295 }296 );297 protected sealed override bool IsValidTestClass(_ITypeInfo type) =>298 base.IsValidTestClass(type);299 public static TestableXunitTestFrameworkDiscoverer Create(300 _IAssemblyInfo? assembly = null,301 IXunitTestCollectionFactory? collectionFactory = null) =>302 new(assembly ?? Mocks.AssemblyInfo(), collectionFactory);303 }304}...

Full Screen

Full Screen

TestMethodTestCaseTests.cs

Source:TestMethodTestCaseTests.cs Github

copy

Full Screen

...4using System.Threading.Tasks;5using Xunit;6using Xunit.Sdk;7using Xunit.v3;8public class TestMethodTestCaseTests9{10 public class Ctor11 {12 [Fact]13 public static void NonSerializableArgumentsThrows()14 {15 var testMethod = Mocks.TestMethod("MockType", "MockMethod");16 var ex = Record.Exception(17 () => new TestableTestMethodTestCase(testMethod, new object[] { new XunitTestCaseTests() })18 );19 Assert.IsType<SerializationException>(ex);20 Assert.Equal($"Type '{typeof(XunitTestCaseTests).FullName}' in Assembly '{typeof(XunitTestCaseTests).Assembly.FullName}' is not marked as serializable.", ex.Message);21 }22 [Fact]23 public static void DefaultBehavior()24 {25 var testMethod = Mocks.TestMethod("MockType", "MockMethod");26 var testCase = new TestableTestMethodTestCase(testMethod);27 Assert.Equal("MockType.MockMethod", testCase.TestCaseDisplayName);28 Assert.Null(testCase.InitializationException);29 Assert.Same(testMethod.Method, testCase.Method);30 Assert.Null(testCase.SkipReason);31 Assert.Null(testCase.SourceFilePath);32 Assert.Null(testCase.SourceLineNumber);33 Assert.Same(testMethod, testCase.TestMethod);34 Assert.Null(testCase.TestMethodArguments);35 Assert.Empty(testCase.Traits);36 Assert.Equal("4428bc4e444a8f5294832dc06425f20fc994bdc44788f03219b7237f892bffe0", testCase.UniqueID);37 }38 [Fact]39 public static void Overrides()40 {41 var testMethod = Mocks.TestMethod("MockType", "Mock_Method");42 var arguments = new object[] { 42, 21.12, "Hello world!" };43 var traits = new Dictionary<string, List<string>> { { "FOO", new List<string> { "BAR" } } };44 var testCase = new TestableTestMethodTestCase(45 testMethod,46 arguments,47 TestMethodDisplay.Method,48 TestMethodDisplayOptions.ReplaceUnderscoreWithSpace,49 "Skip me!",50 traits,51 "test-case-custom-id"52 );53 Assert.Equal($"Mock Method(???: 42, ???: {21.12:G17}, ???: \"Hello world!\")", testCase.TestCaseDisplayName);54 Assert.Equal("Skip me!", testCase.SkipReason);55 Assert.Same(arguments, testCase.TestMethodArguments);56 Assert.Collection(57 testCase.Traits,58 kvp =>59 {60 Assert.Equal("FOO", kvp.Key);61 Assert.Equal("BAR", Assert.Single(kvp.Value));62 }63 );64 Assert.Equal("test-case-custom-id", testCase.UniqueID);65 }66 }67 public class DisplayName68 {69 [Fact]70 public static void CorrectNumberOfTestArguments()71 {72 var param1 = Mocks.ParameterInfo("p1");73 var param2 = Mocks.ParameterInfo("p2");74 var param3 = Mocks.ParameterInfo("p3");75 var testMethod = Mocks.TestMethod(parameters: new[] { param1, param2, param3 });76 var arguments = new object[] { 42, "Hello, world!", 'A' };77 var testCase = new TestableTestMethodTestCase(testMethod, arguments);78 Assert.Equal($"{testMethod.TestClass.Class.Name}.{testMethod.Method.Name}(p1: 42, p2: \"Hello, world!\", p3: 'A')", testCase.TestCaseDisplayName);79 }80 [Fact]81 public static void NotEnoughTestArguments()82 {83 var param = Mocks.ParameterInfo("p1");84 var testMethod = Mocks.TestMethod(parameters: new[] { param });85 var testCase = new TestableTestMethodTestCase(testMethod, new object[0]);86 Assert.Equal($"{testMethod.TestClass.Class.Name}.{testMethod.Method.Name}(p1: ???)", testCase.TestCaseDisplayName);87 }88 [CulturedFact]89 public static void TooManyTestArguments()90 {91 var param = Mocks.ParameterInfo("p1");92 var testMethod = Mocks.TestMethod(parameters: new[] { param });93 var arguments = new object[] { 42, 21.12M };94 var testCase = new TestableTestMethodTestCase(testMethod, arguments);95 Assert.Equal($"{testMethod.TestClass.Class.Name}.{testMethod.Method.Name}(p1: 42, ???: {21.12})", testCase.TestCaseDisplayName);96 }97 [Theory]98 [InlineData(TestMethodDisplay.ClassAndMethod, "TestMethodTestCaseTests+DisplayName.OverrideDefaultMethodDisplay")]99 [InlineData(TestMethodDisplay.Method, "OverrideDefaultMethodDisplay")]100 public static void OverrideDefaultMethodDisplay(101 TestMethodDisplay methodDisplay,102 string expectedDisplayName)103 {104 var testMethod = Mocks.TestMethod<DisplayName>("OverrideDefaultMethodDisplay");105 var testCase = new TestableTestMethodTestCase(testMethod, defaultMethodDisplay: methodDisplay);106 Assert.Equal(expectedDisplayName, testCase.TestCaseDisplayName);107 }108 }109 public class DisposeAsync110 {111 [Fact]112 public static async ValueTask DisposesArguments()113 {114 var disposable = new SerializableDisposable();115 var asyncDisposable = new SerializableAsyncDisposable();116 var testMethod = Mocks.TestMethod();117 var testCase = new TestableTestMethodTestCase(testMethod, new object[] { disposable, asyncDisposable });118 await testCase.DisposeAsync();119 Assert.True(disposable.DisposeCalled);120 Assert.True(asyncDisposable.DisposeAsyncCalled);121 }122 [Serializable]123 class SerializableDisposable : IDisposable124 {125 public bool DisposeCalled = false;126 public void Dispose() => DisposeCalled = true;127 }128 [Serializable]129 class SerializableAsyncDisposable : IAsyncDisposable130 {131 public bool DisposeAsyncCalled = false;132 public ValueTask DisposeAsync()133 {134 DisposeAsyncCalled = true;135 return default;136 }137 }138 }139 public class Method : AcceptanceTestV3140 {141 [Theory(DisableDiscoveryEnumeration = true)]142 [InlineData(42, typeof(int))]143 [InlineData("Hello world", typeof(string))]144 [InlineData(null, typeof(object))]145 public void OpenGenericIsClosedByArguments(146 object? testArg,147 Type expectedGenericType)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 {171 [Theory]172 public void OpenGeneric<T>(T value) { }173 [Theory]174 public void NonGeneric(params int[] values) { }175 }176 }177 public class Serialization178 {179 [Fact]180 public static void CanRoundTrip_PublicClass_PublicTestMethod()181 {182 var testCase = TestableTestMethodTestCase.Create<Serialization>(nameof(CanRoundTrip_PublicClass_PublicTestMethod));183 var serialized = SerializationHelper.Serialize(testCase);184 var deserialized = SerializationHelper.Deserialize<_ITestCase>(serialized);185 Assert.NotNull(deserialized);186 Assert.IsType<TestableTestMethodTestCase>(deserialized);187 }188 [Fact]189 public static void CanRoundTrip_PublicClass_PrivateTestMethod()190 {191 var testCase = TestableTestMethodTestCase.Create<Serialization>(nameof(PrivateTestMethod));192 var serialized = SerializationHelper.Serialize(testCase);193 var deserialized = SerializationHelper.Deserialize<_ITestCase>(serialized);194 Assert.NotNull(deserialized);195 Assert.IsType<TestableTestMethodTestCase>(deserialized);196 }197 [Fact]198 public static void CanRoundTrip_PrivateClass()199 {200 var testCase = TestableTestMethodTestCase.Create<PrivateClass>(nameof(PrivateClass.TestMethod));201 var serialized = SerializationHelper.Serialize(testCase);202 var deserialized = SerializationHelper.Deserialize<_ITestCase>(serialized);203 Assert.NotNull(deserialized);204 Assert.IsType<TestableTestMethodTestCase>(deserialized);205 }206 [Fact]207 void PrivateTestMethod() { }208 class PrivateClass209 {210 [Fact]211 public static void TestMethod()212 {213 Assert.True(false);214 }215 }216 }217 public class Traits218 {219 [Fact]220 public void TraitNamesAreCaseInsensitive_AddedAfter()221 {222 var testMethod = Mocks.TestMethod();223 var testCase = new TestableTestMethodTestCase(testMethod);224 testCase.Traits.Add("FOO", new List<string> { "BAR" });225 var fooTraitValues = testCase.Traits["foo"];226 var fooTraitValue = Assert.Single(fooTraitValues);227 Assert.Equal("BAR", fooTraitValue);228 }229 [Fact]230 public void TraitNamesAreCaseInsensitive_PreSeeded()231 {232 var traits = new Dictionary<string, List<string>> { { "FOO", new List<string> { "BAR" } } };233 var testMethod = Mocks.TestMethod();234 var testCase = new TestableTestMethodTestCase(testMethod, traits: traits);235 var fooTraitValues = testCase.Traits["foo"];236 var fooTraitValue = Assert.Single(fooTraitValues);237 Assert.Equal("BAR", fooTraitValue);238 }239 }240 public class UniqueID241 {242 [Fact]243 public static void UniqueID_NoArguments()244 {245 var uniqueID = TestableTestMethodTestCase.Create<ClassUnderTest>("TestMethod").UniqueID;246 Assert.Equal("4428bc4e444a8f5294832dc06425f20fc994bdc44788f03219b7237f892bffe0", uniqueID);247 }248 [Fact]249 public static void UniqueID_Arguments()250 {251 var uniqueID42 = TestableTestMethodTestCase.Create<ClassUnderTest>("TestMethod", new object?[] { 42 }).UniqueID;252 var uniqueIDHelloWorld = TestableTestMethodTestCase.Create<ClassUnderTest>("TestMethod", new object?[] { "Hello, world!" }).UniqueID;253 var uniqueIDNull = TestableTestMethodTestCase.Create<ClassUnderTest>("TestMethod", new object?[] { null }).UniqueID;254 Assert.Equal("738d958f58f29698b62aa50479dcbb465fc18a500073f46947e60842e79e3e3b", uniqueID42);255 Assert.Equal("7ed69c84a3b325b79c2fd6a8a808033ac0c3f7bdda1a7575c882e69a5dc7ff9a", uniqueIDHelloWorld);256 Assert.Equal("e104382e5370a800728ffb748e92f65ffa3925eb888c4f48238d24c180b8bd48", uniqueIDNull);257 }258 class ClassUnderTest259 {260 [Fact]261 public static void TestMethod() { }262 }263 }264 [Serializable]265 class TestableTestMethodTestCase : TestMethodTestCase266 {267 protected TestableTestMethodTestCase(268 SerializationInfo info,269 StreamingContext context) :270 base(info, context)271 { }272 public TestableTestMethodTestCase(273 _ITestMethod testMethod,274 object?[]? testMethodArguments = null,275 TestMethodDisplay defaultMethodDisplay = TestMethodDisplay.ClassAndMethod,276 TestMethodDisplayOptions defaultMethodDisplayOptions = TestMethodDisplayOptions.None,277 string? skipReason = null,278 Dictionary<string, List<string>>? traits = null,279 string? uniqueID = null)280 : base(defaultMethodDisplay, defaultMethodDisplayOptions, testMethod, testMethodArguments, skipReason, traits, uniqueID)281 { }282 public static TestableTestMethodTestCase Create<TClass>(283 string methodName,284 object?[]? testMethodArguments = null)285 {286 var testMethod = TestData.TestMethod<TClass>(methodName);287 return new TestableTestMethodTestCase(testMethod, testMethodArguments);288 }289 }290}...

Full Screen

Full Screen

XunitTestCaseTests.cs

Source:XunitTestCaseTests.cs Github

copy

Full Screen

...4using System.Runtime.Serialization;5using Xunit;6using Xunit.Sdk;7using Xunit.v3;8public class XunitTestCaseTests9{10 public class FactAttributeValues11 {12 [Fact]13 public static void DisplayName()14 {15 var factAttribute = Mocks.FactAttribute(displayName: "Custom Display Name");16 var testMethod = Mocks.TestMethod(methodAttributes: new[] { factAttribute });17 var testCase = new TestableXunitTestCase(testMethod);18 Assert.Equal("Custom Display Name", testCase.TestCaseDisplayName);19 }20 [Fact]21 public static void DisplayNameWithArguments()22 {23 var factAttribute = Mocks.FactAttribute(displayName: "Custom Display Name");24 var param1 = Mocks.ParameterInfo("p1");25 var param2 = Mocks.ParameterInfo("p2");26 var param3 = Mocks.ParameterInfo("p3");27 var testMethod = Mocks.TestMethod(methodAttributes: new[] { factAttribute }, parameters: new[] { param1, param2, param3 });28 var arguments = new object[] { 42, "Hello, world!", 'A' };29 var testCase = new TestableXunitTestCase(testMethod, arguments);30 Assert.Equal("Custom Display Name(p1: 42, p2: \"Hello, world!\", p3: 'A')", testCase.TestCaseDisplayName);31 }32 [Fact]33 public static void SkipReason()34 {35 var factAttribute = Mocks.FactAttribute(skip: "Skip Reason");36 var testMethod = Mocks.TestMethod(methodAttributes: new[] { factAttribute });37 var testCase = new TestableXunitTestCase(testMethod);38 Assert.Equal("Skip Reason", testCase.SkipReason);39 }40 [Fact]41 public static void Timeout()42 {43 var factAttribute = Mocks.FactAttribute(timeout: 42);44 var testMethod = Mocks.TestMethod(methodAttributes: new[] { factAttribute });45 var testCase = new TestableXunitTestCase(testMethod);46 Assert.Equal(42, testCase.Timeout);47 }48 }49 public class Traits : AcceptanceTestV350 {51 [Fact]52 public static void TraitsOnTestMethod()53 {54 var trait1 = Mocks.TraitAttribute("Trait1", "Value1");55 var trait2 = Mocks.TraitAttribute("Trait2", "Value2");56 var testMethod = Mocks.TestMethod(methodAttributes: new[] { trait1, trait2 });57 var testCase = new TestableXunitTestCase(testMethod);58 Assert.Equal("Value1", Assert.Single(testCase.Traits["Trait1"]));59 Assert.Equal("Value2", Assert.Single(testCase.Traits["Trait2"]));60 }61 [Fact]62 public static void TraitsOnTestClass()63 {64 var trait1 = Mocks.TraitAttribute("Trait1", "Value1");65 var trait2 = Mocks.TraitAttribute("Trait2", "Value2");66 var testMethod = Mocks.TestMethod(classAttributes: new[] { trait1, trait2 });67 var testCase = new TestableXunitTestCase(testMethod);68 Assert.Equal("Value1", Assert.Single(testCase.Traits["Trait1"]));69 Assert.Equal("Value2", Assert.Single(testCase.Traits["Trait2"]));70 }71 [Fact]72 public async void CustomTrait()73 {74 var messages = await RunAsync(typeof(ClassWithCustomTraitTest));75 var passingTests = messages.OfType<_TestPassed>();76 var passingTest = Assert.Single(passingTests);77 var passingTestCaseStarting = messages.OfType<_TestCaseStarting>().Single(tcs => tcs.TestCaseUniqueID == passingTest.TestCaseUniqueID);78 Assert.Collection(79 passingTestCaseStarting.Traits.OrderBy(x => x.Key),80 namedTrait =>81 {82 Assert.Equal("Assembly", namedTrait.Key);83 var value = Assert.Single(namedTrait.Value);84 Assert.Equal("Trait", value);85 },86 namedTrait =>87 {88 Assert.Equal("Author", namedTrait.Key);89 var value = Assert.Single(namedTrait.Value);90 Assert.Equal("Some Schmoe", value);91 },92 namedTrait =>93 {94 Assert.Equal("Bug", namedTrait.Key);95 var value = Assert.Single(namedTrait.Value);96 Assert.Equal("2112", value);97 }98 );99 }100 [Fact]101 public static void CustomTraitWithoutDiscoverer()102 {103 var spy = SpyMessageSink.Capture();104 TestContext.Current!.DiagnosticMessageSink = spy;105 var trait = Mocks.TraitAttribute<BadTraitAttribute>();106 var testMethod = Mocks.TestMethod(classAttributes: new[] { trait });107 var testCase = new TestableXunitTestCase(testMethod);108 Assert.Empty(testCase.Traits);109 var diagnosticMessages = spy.Messages.OfType<_DiagnosticMessage>();110 var diagnosticMessage = Assert.Single(diagnosticMessages);111 Assert.Equal($"Trait attribute on '{testCase.TestCaseDisplayName}' did not have [TraitDiscoverer]", diagnosticMessage.Message);112 }113 class BadTraitAttribute : Attribute, ITraitAttribute { }114 class ClassWithCustomTraitTest115 {116 [Fact]117 [Bug(2112)]118 [Trait("Author", "Some Schmoe")]119 public static void BugFix() { }120 }121 public class BugDiscoverer : ITraitDiscoverer122 {123 public IReadOnlyCollection<KeyValuePair<string, string>> GetTraits(_IAttributeInfo traitAttribute)124 {125 var ctorArgs = traitAttribute.GetConstructorArguments().ToList();126 return new[] { new KeyValuePair<string, string>("Bug", ctorArgs[0]!.ToString()!) };127 }128 }129 [TraitDiscoverer(typeof(BugDiscoverer))]130 class BugAttribute : Attribute, ITraitAttribute131 {132 public BugAttribute(int id) { }133 }134 public static TheoryData<Type, IEnumerable<string>> CustomAttributeTestCases() =>135 new()136 {137 { typeof(ClassWithSingleTrait), new[] { "One" } },138 { typeof(ClassWithMultipleTraits), new[] { "One", "Two" } },139 { typeof(InheritedClassWithOnlyOwnTrait), new[] { "One" } },140 { typeof(InheritedClassWithOnlyOwnMultipleTraits), new[] { "One", "Two" } },141 { typeof(InheritedClassWithSingleBaseClassTrait), new[] { "BaseOne" } },142 { typeof(InheritedClassWithMultipleBaseClassTraits), new[] { "BaseOne", "BaseTwo" } },143 { typeof(InheritedClassWithOwnSingleTraitAndSingleBaseClassTrait), new[] { "One", "BaseOne" } },144 { typeof(InheritedClassWithOwnSingleTraitAndMultipleBaseClassTrait), new[] { "One", "BaseOne", "BaseTwo" } },145 { typeof(InheritedClassWithOwnMultipleTraitsAndSingleBaseClassTrait), new[] { "One", "Two", "BaseOne" } },146 { typeof(InheritedClassWithOwnMultipleTraitsAndMultipleBaseClassTrait), new[] { "One", "Two", "BaseOne", "BaseTwo" } }147 };148 [Theory(DisableDiscoveryEnumeration = true)]149 [MemberData(nameof(CustomAttributeTestCases))]150 public void ReturnsCorrectCustomAttributes(Type classType, IEnumerable<string> expectedTraits)151 {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 BaseClassWithMultipleTraits171 { }172 [Trait("Test", "One")]173 class ClassWithSingleTrait174 {175 [Fact]176 public void TraitsTest()177 { }178 }179 [Trait("Test", "One"), Trait("Test", "Two")]180 class ClassWithMultipleTraits181 {182 [Fact]183 public void TraitsTest()184 { }185 }186 [Trait("Test", "One")]187 class InheritedClassWithOnlyOwnTrait : BaseClassWithoutTraits188 {189 [Fact]190 public void TraitsTest()191 { }192 }193 [Trait("Test", "One"), Trait("Test", "Two")]194 class InheritedClassWithOnlyOwnMultipleTraits : BaseClassWithoutTraits195 {196 [Fact]197 public void TraitsTest()198 { }199 }200 class InheritedClassWithSingleBaseClassTrait : BaseClassWithSingleTrait201 {202 [Fact]203 public void TraitsTest()204 { }205 }206 class InheritedClassWithMultipleBaseClassTraits : BaseClassWithMultipleTraits207 {208 [Fact]209 public void TraitsTest()210 { }211 }212 [Trait("Test", "One")]213 class InheritedClassWithOwnSingleTraitAndSingleBaseClassTrait : BaseClassWithSingleTrait214 {215 [Fact]216 public void TraitsTest()217 { }218 }219 [Trait("Test", "One")]220 class InheritedClassWithOwnSingleTraitAndMultipleBaseClassTrait : BaseClassWithMultipleTraits221 {222 [Fact]223 public void TraitsTest()224 { }225 }226 [Trait("Test", "One"), Trait("Test", "Two")]227 class InheritedClassWithOwnMultipleTraitsAndSingleBaseClassTrait : BaseClassWithSingleTrait228 {229 [Fact]230 public void TraitsTest()231 { }232 }233 [Trait("Test", "One"), Trait("Test", "Two")]234 class InheritedClassWithOwnMultipleTraitsAndMultipleBaseClassTrait : BaseClassWithMultipleTraits235 {236 [Fact]237 public void TraitsTest()238 { }239 }240 }241 [Serializable]242 class TestableXunitTestCase : XunitTestCase243 {244 protected TestableXunitTestCase(245 SerializationInfo info,246 StreamingContext context) :247 base(info, context)248 { }249 public TestableXunitTestCase(250 _ITestMethod testMethod,251 object?[]? testMethodArguments = null) :252 base(TestMethodDisplay.ClassAndMethod, TestMethodDisplayOptions.None, testMethod, testMethodArguments, null, null, null, null, null)253 { }254 }255}...

Full Screen

Full Screen

ProjectRequestAccessTests.cs

Source:ProjectRequestAccessTests.cs Github

copy

Full Screen

1using System;2using System.Linq;3using System.Net;4using System.Net.Http;5using System.Threading.Tasks;6using Fusion.ApiClients.Org;7using Fusion.Integration.Profile;8using Fusion.Integration.Profile.ApiClient;9using Fusion.Resources.Api.Tests.Fixture;10using Fusion.Testing;11using Fusion.Testing.Authentication.User;12using Fusion.Testing.Mocks;13using Fusion.Testing.Mocks.OrgService;14using Fusion.Testing.Mocks.ProfileService;15using Xunit;16using Xunit.Abstractions;17#nullable enable 18namespace Fusion.Resources.Api.Tests.IntegrationTests19{20 public class ProjectRequestAccessTests : IClassFixture<ResourceApiFixture>, IAsyncLifetime21 {22 private readonly ResourceApiFixture fixture;23 private readonly TestLoggingScope loggingScope;24 /// <summary>25 /// Will be generated new for each test26 /// </summary>27 private ApiPersonProfileV3 testUser;28 // Created by the async lifetime29 private TestApiInternalRequestModel normalRequest = null!;30 private FusionTestProjectBuilder testProject = null!;31 private Guid projectId => testProject.Project.ProjectId;32 public ProjectRequestAccessTests(ResourceApiFixture fixture, ITestOutputHelper output)33 {34 this.fixture = fixture;35 // Make the output channel available for TestLogger.TryLog and the TestClient* calls.36 loggingScope = new TestLoggingScope(output);37 // Generate random test user38 testUser = fixture.AddProfile(FusionAccountType.External);39 }40 private HttpClient Client => fixture.ApiFactory.CreateClient();41 public async Task InitializeAsync()42 {43 // Mock profile44 testUser = PeopleServiceMock.AddTestProfile()45 .SaveProfile();46 // Mock project47 testProject = new FusionTestProjectBuilder()48 .WithPositions(200)49 .AddToMockService();50 // Prepare context resolver.51 fixture.ContextResolver52 .AddContext(testProject.Project);53 // Prepare admin client54 var adminClient = fixture.ApiFactory.CreateClient()55 .WithTestUser(fixture.AdminUser)56 .AddTestAuthToken();57 // Create a default request we can work with58 normalRequest = await adminClient.CreateDefaultRequestAsync(testProject, r => r.AsTypeNormal());59 }60 [Theory]61 [InlineData("projectMember", true)]62 [InlineData("normalEmployee", false)]63 public async Task GetProjectRequests_When(string testCase, bool shouldHaveAccess)64 { 65 var projectMemberUser = fixture.AddProfile(FusionAccountType.Employee);66 67 if (testCase == "projectMember")68 projectMemberUser.WithPosition(testProject.AddPosition().WithEnsuredFutureInstances().WithAssignedPerson(projectMemberUser));69 using var projectMemberScope = fixture.UserScope(projectMemberUser);70 var resp = await Client.TestClientGetAsync<object>($"/projects/{projectId}/resources/requests");71 72 if (shouldHaveAccess)73 resp.Should().BeSuccessfull();74 else75 resp.Should().BeUnauthorized();76 }77 [Theory]78 [InlineData("projectReadAccess", true)]79 [InlineData("projectMember", true)]80 [InlineData("normalEmployee", false)]81 public async Task GetRequestInProject_When(string testCase, bool shouldHaveAccess)82 {83 OrgRequestInterceptor? i = null;84 var projectMemberUser = fixture.AddProfile(FusionAccountType.Employee);85 if (testCase == "projectMember")86 projectMemberUser.WithPosition(testProject.AddPosition().WithEnsuredFutureInstances().WithAssignedPerson(projectMemberUser));87 if (testCase == "projectReadAccess")88 i = OrgRequestMocker.InterceptOption($"/{projectId}").RespondWithHeaders(HttpStatusCode.NoContent, h => h.Add("Allow", "GET"));89 using var projectMemberScope = fixture.UserScope(projectMemberUser);90 var resp = await Client.TestClientGetAsync<object>($"/projects/{projectId}/resources/requests/{normalRequest.Id}");91 if (shouldHaveAccess)92 resp.Should().BeSuccessfull();93 else94 resp.Should().BeUnauthorized();95 if (i != null)96 i.Dispose();97 }98 [Fact]99 public async Task StartAllocationRequest_ShouldHaveAccess_WhenEditAccessOnPosition()100 {101 // Setup org api mock to return PUT in option call102 using var i = OrgRequestMocker.InterceptOption($"/{normalRequest.OrgPositionId}").RespondWithHeaders(HttpStatusCode.NoContent, h => h.Add("Allow", "PUT"));103 104 var projectMemberUser = fixture.AddProfile(FusionAccountType.Employee);105 using var projectMemberScope = fixture.UserScope(projectMemberUser);106 var resp = await Client.TestClientPostAsync<object>($"/projects/{projectId}/resources/requests/{normalRequest.Id}/start", null);107 resp.Should().BeSuccessfull();108 }109 [Fact]110 public async Task StartAllocationRequest_ShouldNotAccess_WhenProjectMember()111 {112 var projectMemberUser = fixture.AddProfile(FusionAccountType.Employee);113 projectMemberUser.WithPosition(testProject.AddPosition().WithEnsuredFutureInstances().WithAssignedPerson(projectMemberUser));114 using var projectMemberScope = fixture.UserScope(projectMemberUser);115 var resp = await Client.TestClientPostAsync<object>($"/projects/{projectId}/resources/requests/{normalRequest.Id}/start", null);116 resp.Should().BeUnauthorized();117 }118 119 public Task DisposeAsync() => Task.CompletedTask;120 }121 public static class ApiPersonProfileV3Extensions122 {123 public static ApiPersonProfileV3 WithPosition(this ApiPersonProfileV3 profile, ApiPositionV2 position)124 {125 var personPositions = position.Instances126 .Where(i => i.AssignedPerson?.AzureUniqueId == profile.AzureUniqueId)127 .Select(i => new ApiPersonPositionV3()128 {129 AppliesFrom = i.AppliesFrom,130 AppliesTo = i.AppliesTo,131 Id = i.Id,132 BasePosition = new ApiPersonBasePositionV3()133 {134 Id = position.BasePosition.Id,135 Discipline = position.BasePosition.Discipline,136 Name = position.BasePosition.Name,137 SubDiscipline = position.BasePosition.SubDiscipline,138 Type = position.BasePosition.ProjectType139 },140 Name = position.Name,141 Obs = i.Obs,142 ParentPositionId = i.ParentPositionId,143 PositionExternalId = position.ExternalId,144 PositionId = position.Id,145 Project = new ApiPersonPositionProjectV3()146 {147 Id = position.ProjectId,148 DomainId = position.Project.DomainId,149 Name = position.Project.Name,150 Type = position.Project.ProjectType151 },152 Workload = i.Workload,153 TaskOwnerIds = i.TaskOwnerIds154 }).ToList();155 if (profile.Positions is null)156 profile.Positions = new System.Collections.Generic.List<ApiPersonPositionV3>();157 profile.Positions.AddRange(personPositions);158 return profile;159 }160 }161}...

Full Screen

Full Screen

FactDiscovererTests.cs

Source:FactDiscovererTests.cs Github

copy

Full Screen

...20 messageBus = new SpyMessageBus();21 options = _TestFrameworkOptions.ForDiscovery();22 }23 [Fact]24 public async void FactWithoutParameters_ReturnsTestCaseThatRunsFact()25 {26 var discoverer = new FactDiscoverer();27 var testMethod = Mocks.TestMethod<ClassUnderTest>("FactWithNoParameters");28 var testCases = await discoverer.Discover(options, testMethod, factAttribute);29 var testCase = Assert.Single(testCases);30 await testCase.RunAsync(messageBus, new object[0], aggregator, cancellationTokenSource);31 Assert.Single(messageBus.Messages.OfType<_TestPassed>());32 }33 [Fact]34 public async void FactWithParameters_ReturnsTestCaseWhichThrows()35 {36 var discoverer = new FactDiscoverer();37 var testMethod = Mocks.TestMethod<ClassUnderTest>("FactWithParameters");38 var testCases = await discoverer.Discover(options, testMethod, factAttribute);39 var testCase = Assert.Single(testCases);40 await testCase.RunAsync(messageBus, new object[0], aggregator, cancellationTokenSource);41 var failed = Assert.Single(messageBus.Messages.OfType<_TestFailed>());42 Assert.Equal(typeof(InvalidOperationException).FullName, failed.ExceptionTypes.Single());43 Assert.Equal("[Fact] methods are not allowed to have parameters. Did you mean to use [Theory]?", failed.Messages.Single());44 }45 [Fact]46 public async void GenericFact_ReturnsTestCaseWhichThrows()47 {48 var discoverer = new FactDiscoverer();49 var testMethod = Mocks.TestMethod<ClassUnderTest>("GenericFact");50 var testCases = await discoverer.Discover(options, testMethod, factAttribute);51 var testCase = Assert.Single(testCases);52 await testCase.RunAsync(messageBus, new object[0], aggregator, cancellationTokenSource);53 var failed = Assert.Single(messageBus.Messages.OfType<_TestFailed>());54 Assert.Equal(typeof(InvalidOperationException).FullName, failed.ExceptionTypes.Single());55 Assert.Equal("[Fact] methods are not allowed to be generic.", failed.Messages.Single());56 }57 class ClassUnderTest58 {59 [Fact]60 public void FactWithNoParameters() { }...

Full Screen

Full Screen

DefaultTestCaseOrdererTests.cs

Source:DefaultTestCaseOrdererTests.cs Github

copy

Full Screen

1using System;2using Xunit;3using Xunit.v3;4public class DefaultTestCaseOrdererTests5{6 static readonly _ITestCase[] TestCases = new[] {7 Mocks.TestCase<ClassUnderTest>("Test1", uniqueID: $"test-case-{Guid.NewGuid():n}"),8 Mocks.TestCase<ClassUnderTest>("Test2", uniqueID: $"test-case-{Guid.NewGuid():n}"),9 Mocks.TestCase<ClassUnderTest>("Test3", uniqueID: $"test-case-{Guid.NewGuid():n}"),10 Mocks.TestCase<ClassUnderTest>("Test4", uniqueID: $"test-case-{Guid.NewGuid():n}"),11 Mocks.TestCase<ClassUnderTest>("Test3", uniqueID: $"test-case-{Guid.NewGuid():n}"),12 Mocks.TestCase<ClassUnderTest>("Test5", uniqueID: $"test-case-{Guid.NewGuid():n}"),13 Mocks.TestCase<ClassUnderTest>("Test6", uniqueID: $"test-case-{Guid.NewGuid():n}")14 };15 [Fact]16 public static void OrderIsStable()17 {18 var orderer = new DefaultTestCaseOrderer();19 var result1 = orderer.OrderTestCases(TestCases);20 var result2 = orderer.OrderTestCases(TestCases);21 var result3 = orderer.OrderTestCases(TestCases);22 Assert.Equal(result1, result2);23 Assert.Equal(result2, result3);24 }25 [Fact]26 public static void OrderIsUnpredictable()27 {28 var orderer = new DefaultTestCaseOrderer();29 var result = orderer.OrderTestCases(TestCases);30 Assert.NotEqual(TestCases, result);31 }32 class ClassUnderTest33 {34 [Fact]35 public void Test1() { }36 [Fact]37 public void Test2() { }38 [Fact]39 public void Test3() { }40 [Fact]41 public void Test4() { }42 [Fact]43 public void Test5() { }44 [Fact]...

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1using Xunit;2{3 {4 public static TestCase<T> Create<T>(T value)5 {6 return new TestCase<T>(value);7 }8 }9}10using Xunit.v3.Mocks;11{12 {13 public T Value { get; }14 public TestCase(T value)15 {16 Value = value;17 }18 }19}20using Xunit.v3.Mocks;21using Xunit;22{23 {24 public T Value { get; }25 public TestCase(T value)26 {27 Value = value;28 }29 }30}31using Xunit.v3.Mocks;32using Xunit;33{34 {35 public T Value { get; }36 public TestCase(T value)37 {38 Value = value;39 }40 }41}42using Xunit.v3.Mocks;43using Xunit;44{45 {46 public T Value { get; }47 public TestCase(T value)48 {49 Value = value;50 }51 }52}53using Xunit.v3.Mocks;54using Xunit;55{56 {57 public T Value { get; }58 public TestCase(T value)59 {60 Value = value;61 }62 }63}64using Xunit.v3.Mocks;65using Xunit;66{67 {68 public T Value { get; }69 public TestCase(T value)70 {71 Value = value;72 }73 }74}

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3;3{4 public void Test1()5 {6 var mock = new Mocks();7 var testCase = mock.TestCase<TestClass>("Test1");8 Assert.NotNull(testCase);9 }10}11using Xunit;12using Xunit.v3;13{14 [InlineData(1)]15 [InlineData(2)]16 public void Test1(int a)17 {18 var mock = new Mocks();19 var testCase = mock.TestCase<TestClass>("Test1", a);20 Assert.NotNull(testCase);21 }22}23using Xunit;24using Xunit.v3;25{26 [InlineData(1, 2)]27 [InlineData(2, 3)]28 public void Test1(int a, int b)29 {30 var mock = new Mocks();31 var testCase = mock.TestCase<TestClass>("Test1", a, b);32 Assert.NotNull(testCase);33 }34}35using Xunit;36using Xunit.v3;37{38 [InlineData(1, 2, 3)]39 [InlineData(2, 3, 4)]40 public void Test1(int a, int b, int c)41 {42 var mock = new Mocks();43 var testCase = mock.TestCase<TestClass>("Test1", a, b, c);44 Assert.NotNull(testCase);45 }46}47using Xunit;48using Xunit.v3;49{50 [InlineData(1, 2, 3, 4)]51 [InlineData(2, 3, 4, 5)]52 public void Test1(int a, int b, int c, int d)53 {54 var mock = new Mocks();55 var testCase = mock.TestCase<TestClass>("Test1", a, b, c, d);56 Assert.NotNull(testCase);57 }58}

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2using Xunit.v3;3using Xunit.v2;4{5 {6 public void TestMethod()7 {8 var testCase = TestCase("TestMethod", "Class1");9 }10 }11}12using Xunit.v3.Mocks;13using Xunit.v3;14using Xunit.v2;15{16 {17 public void TestMethod()18 {19 var testCase = TestCase("TestMethod", "Class1");20 }21 }22}23using Xunit.v3.Mocks;24using Xunit.v3;25using Xunit.v2;26{27 {28 public void TestMethod()29 {30 var testCase = TestCase("TestMethod", "Class1");31 }32 }33}34using Xunit.v3.Mocks;35using Xunit.v3;36using Xunit.v2;37{38 {39 public void TestMethod()40 {41 var testCase = TestCase("TestMethod", "Class1");42 }43 }44}45using Xunit.v3.Mocks;46using Xunit.v3;47using Xunit.v2;48{49 {50 public void TestMethod()51 {52 var testCase = TestCase("TestMethod", "Class1");53 }54 }55}56using Xunit.v3.Mocks;57using Xunit.v3;58using Xunit.v2;59{60 {61 public void TestMethod()62 {63 var testCase = TestCase("TestMethod", "Class1");64 }65 }66}67using Xunit.v3.Mocks;68using Xunit.v3;

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2using Xunit.v3;3{4 {5 [TestCase("Hello", 5)]6 [TestCase("Hi", 2)]7 public void MyTest(string input, int expected)8 {9 Assert.Equal(expected, input.Length);10 }11 }12}13using Xunit.v3.Mocks;14using Xunit.v3;15{16 {17 [TestCase("Hello", 5)]18 [TestCase("Hi", 2)]19 public void MyTest(string input, int expected)20 {21 Assert.Equal(expected, input.Length);22 }23 }24}25using Xunit.v3.Mocks;26using Xunit.v3;27{28 {29 [TestCase("Hello", 5)]30 [TestCase("Hi", 2)]31 public void MyTest(string input, int expected)32 {33 Assert.Equal(expected, input.Length);34 }35 }36}37using Xunit.v3.Mocks;38using Xunit.v3;39{40 {41 [TestCase("Hello", 5)]42 [TestCase("Hi", 2)]43 public void MyTest(string input, int expected)44 {45 Assert.Equal(expected, input.Length);46 }47 }48}49using Xunit.v3.Mocks;50using Xunit.v3;51{52 {53 [TestCase("Hello", 5)]54 [TestCase("Hi", 2)]55 public void MyTest(string input, int expected)56 {57 Assert.Equal(expected, input.Length);58 }59 }60}61public static ITestCaseBuilder TestCase(this ITestCaseBuilder builder, object[] arguments)

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2using Xunit.v3;3public class TestClass {4 [TestCase("a", "b")]5 public void TestMethod(string a, string b) {6 }7}8using Xunit.v3.Mocks;9using Xunit.v3;10public class TestClass {11 [TestCase("a", "b")]12 public void TestMethod(string a, string b) {13 }14}15using Xunit.v3.Mocks;16using Xunit.v3;17public class TestClass {18 [TestCase("a", "b")]19 public void TestMethod(string a, string b) {20 }21}22using Xunit.v3.Mocks;23using Xunit.v3;24public class TestClass {25 [TestCase("a", "b")]26 public void TestMethod(string a, string b) {27 }28}29using Xunit.v3.Mocks;30using Xunit.v3;31public class TestClass {32 [TestCase("a", "b")]33 public void TestMethod(string a, string b) {34 }35}36using Xunit.v3.Mocks;37using Xunit.v3;38public class TestClass {39 [TestCase("a", "b")]40 public void TestMethod(string a, string b) {41 }42}43using Xunit.v3.Mocks;44using Xunit.v3;45public class TestClass {46 [TestCase("a", "b")]47 public void TestMethod(string a, string b) {48 }49}50using Xunit.v3.Mocks;51using Xunit.v3;52public class TestClass {53 [TestCase("a", "b")]

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1public void TestMethod1()2{3 var testCase = Xunit.v3.Mocks.TestCase<2>("TestMethod1");4 Assert.Equal("TestMethod1", testCase.DisplayName);5 Assert.Equal("2.cs", testCase.SourceInformation.FileName);6 Assert.Equal(2, testCase.SourceInformation.LineNumber);7}8public void TestMethod1()9{10 var testCase = Xunit.v3.Mocks.TestCase<3>("TestMethod1");11 Assert.Equal("TestMethod1", testCase.DisplayName);12 Assert.Equal("3.cs", testCase.SourceInformation.FileName);13 Assert.Equal(2, testCase.SourceInformation.LineNumber);14}15public void TestMethod1()16{17 var testCase = Xunit.v3.Mocks.TestCase<4>("TestMethod1");18 Assert.Equal("TestMethod1", testCase.DisplayName);19 Assert.Equal("4.cs", testCase.SourceInformation.FileName);20 Assert.Equal(2, testCase.SourceInformation.LineNumber);21}22public void TestMethod1()23{24 var testCase = Xunit.v3.Mocks.TestCase<5>("TestMethod1");25 Assert.Equal("TestMethod1", testCase.DisplayName);26 Assert.Equal("5.cs", testCase.SourceInformation.FileName);27 Assert.Equal(2, testCase.SourceInformation.LineNumber);28}29public void TestMethod1()30{31 var testCase = Xunit.v3.Mocks.TestCase<6>("TestMethod1");32 Assert.Equal("TestMethod1", testCase.DisplayName);33 Assert.Equal("6.cs", testCase.SourceInformation.FileName);34 Assert.Equal(2, testCase.SourceInformation.LineNumber);35}36public void TestMethod1()37{38 var testCase = Xunit.v3.Mocks.TestCase<7>("TestMethod1");39 Assert.Equal("TestMethod1", testCase.DisplayName);40 Assert.Equal("7.cs", testCase.SourceInformation

Full Screen

Full Screen

TestCase

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2using Xunit;3using System;4using System.Collections.Generic;5using Xunit.v3;6{7 {8 public void Test()9 {10 var testClass = TestCase.CreateTestClass(11 new List<string> { "Test2.Test2.cs" },12 new List<string> { "Test2.Test2.cs" });13 var testCases = TestCase.CreateTestCases(14 new List<string> { "Test2.Test2.cs" });15 TestCase.AddTestMethods(testClass, testCases);16 var testAssembly = TestCase.CreateTestAssembly(17 new List<TestClass> { testClass });18 var testCollection = TestCase.CreateTestCollection(19 new List<TestAssembly> { testAssembly });20 var test = TestCase.CreateTest(21 new List<string> { "Test2.Test2.cs" });22 var testResult = TestCase.RunTest(test);23 Console.WriteLine(testResult);24 }25 }26}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful