Best Xunit code snippet using Xunit.v3.Mocks
XunitTestAssemblyRunnerContextTests.cs
Source:XunitTestAssemblyRunnerContextTests.cs
...33 }34 [Fact]35 public static async ValueTask Attribute_NonParallel()36 {37 var attribute = Mocks.CollectionBehaviorAttribute(disableTestParallelization: true);38 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { attribute });39 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);40 await context.InitializeAsync();41 var result = context.TestFrameworkEnvironment;42 Assert.EndsWith("[collection-per-class, non-parallel]", result);43 }44 [Fact]45 public static async ValueTask Attribute_MaxThreads()46 {47 var attribute = Mocks.CollectionBehaviorAttribute(maxParallelThreads: 3);48 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { attribute });49 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);50 await context.InitializeAsync();51 var result = context.TestFrameworkEnvironment;52 Assert.EndsWith("[collection-per-class, parallel (3 threads)]", result);53 }54 [Fact]55 public static async ValueTask Attribute_Unlimited()56 {57 var attribute = Mocks.CollectionBehaviorAttribute(maxParallelThreads: -1);58 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { attribute });59 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);60 await context.InitializeAsync();61 var result = context.TestFrameworkEnvironment;62 Assert.EndsWith("[collection-per-class, parallel (unlimited threads)]", result);63 }64 [Theory]65 [InlineData(CollectionBehavior.CollectionPerAssembly, "collection-per-assembly")]66 [InlineData(CollectionBehavior.CollectionPerClass, "collection-per-class")]67 public static async ValueTask Attribute_CollectionBehavior(CollectionBehavior behavior, string expectedDisplayText)68 {69 var attribute = Mocks.CollectionBehaviorAttribute(behavior, disableTestParallelization: true);70 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { attribute });71 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);72 await context.InitializeAsync();73 var result = context.TestFrameworkEnvironment;74 Assert.EndsWith($"[{expectedDisplayText}, non-parallel]", result);75 }76 [Fact]77 public static async ValueTask Attribute_CustomCollectionFactory()78 {79 var factoryType = typeof(MyTestCollectionFactory);80 var attr = Mocks.CollectionBehaviorAttribute(factoryType.FullName!, factoryType.Assembly.FullName!, disableTestParallelization: true);81 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { attr });82 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);83 await context.InitializeAsync();84 var result = context.TestFrameworkEnvironment;85 Assert.EndsWith("[My Factory, non-parallel]", result);86 }87 class MyTestCollectionFactory : IXunitTestCollectionFactory88 {89 public string DisplayName { get { return "My Factory"; } }90 public MyTestCollectionFactory(_ITestAssembly assembly) { }91 public _ITestCollection Get(_ITypeInfo testClass)92 {93 throw new NotImplementedException();94 }95 }96 [Fact]97 public static async ValueTask TestOptions_NonParallel()98 {99 var options = _TestFrameworkOptions.ForExecution();100 options.SetDisableParallelization(true);101 await using var context = TestableXunitTestAssemblyRunnerContext.Create(executionOptions: options);102 await context.InitializeAsync();103 var result = context.TestFrameworkEnvironment;104 Assert.EndsWith("[collection-per-class, non-parallel]", result);105 }106 [Fact]107 public static async ValueTask TestOptions_MaxThreads()108 {109 var options = _TestFrameworkOptions.ForExecution();110 options.SetMaxParallelThreads(3);111 await using var context = TestableXunitTestAssemblyRunnerContext.Create(executionOptions: options);112 await context.InitializeAsync();113 var result = context.TestFrameworkEnvironment;114 Assert.EndsWith("[collection-per-class, parallel (3 threads)]", result);115 }116 [Fact]117 public static async ValueTask TestOptions_Unlimited()118 {119 var options = _TestFrameworkOptions.ForExecution();120 options.SetMaxParallelThreads(-1);121 await using var context = TestableXunitTestAssemblyRunnerContext.Create(executionOptions: options);122 await context.InitializeAsync();123 var result = context.TestFrameworkEnvironment;124 Assert.EndsWith("[collection-per-class, parallel (unlimited threads)]", result);125 }126 [Fact]127 public static async ValueTask TestOptionsOverrideAttribute()128 {129 var attribute = Mocks.CollectionBehaviorAttribute(disableTestParallelization: true, maxParallelThreads: 127);130 var options = _TestFrameworkOptions.ForExecution();131 options.SetDisableParallelization(false);132 options.SetMaxParallelThreads(3);133 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { attribute });134 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly, executionOptions: options);135 await context.InitializeAsync();136 var result = context.TestFrameworkEnvironment;137 Assert.EndsWith("[collection-per-class, parallel (3 threads)]", result);138 }139 }140 public class AssemblyTestCaseOrderer141 {142 [Fact]143 public static async ValueTask CanSetTestCaseOrdererInAssemblyAttribute()144 {145 var ordererAttribute = Mocks.TestCaseOrdererAttribute<MyTestCaseOrderer>();146 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { ordererAttribute });147 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);148 await context.InitializeAsync();149 var result = context.AssemblyTestCaseOrderer;150 Assert.IsType<MyTestCaseOrderer>(result);151 }152 class MyTestCaseOrderer : ITestCaseOrderer153 {154 public IReadOnlyCollection<TTestCase> OrderTestCases<TTestCase>(IReadOnlyCollection<TTestCase> testCases)155 where TTestCase : notnull, _ITestCase156 {157 throw new NotImplementedException();158 }159 }160 [Fact]161 public static async ValueTask SettingUnknownTestCaseOrderLogsDiagnosticMessage()162 {163 var spy = SpyMessageSink.Capture();164 TestContext.Current!.DiagnosticMessageSink = spy;165 var ordererAttribute = Mocks.TestCaseOrdererAttribute("UnknownType", "UnknownAssembly");166 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { ordererAttribute });167 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);168 await context.InitializeAsync();169 var result = context.AssemblyTestCaseOrderer;170 Assert.Null(result);171 var diagnosticMessage = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());172 Assert.Equal("Could not find type 'UnknownType' in UnknownAssembly for assembly-level test case orderer", diagnosticMessage.Message);173 }174 [Fact]175 public static async ValueTask SettingTestCaseOrdererWithThrowingConstructorLogsDiagnosticMessage()176 {177 var spy = SpyMessageSink.Capture();178 TestContext.Current!.DiagnosticMessageSink = spy;179 var ordererAttribute = Mocks.TestCaseOrdererAttribute<MyCtorThrowingTestCaseOrderer>();180 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { ordererAttribute });181 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);182 await context.InitializeAsync();183 var result = context.AssemblyTestCaseOrderer;184 Assert.Null(result);185 var diagnosticMessage = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());186 Assert.StartsWith($"Assembly-level test case orderer '{typeof(MyCtorThrowingTestCaseOrderer).FullName}' threw 'System.DivideByZeroException' during construction: Attempted to divide by zero.", diagnosticMessage.Message);187 }188 class MyCtorThrowingTestCaseOrderer : ITestCaseOrderer189 {190 public MyCtorThrowingTestCaseOrderer()191 {192 throw new DivideByZeroException();193 }194 public IReadOnlyCollection<TTestCase> OrderTestCases<TTestCase>(IReadOnlyCollection<TTestCase> testCases)195 where TTestCase : notnull, _ITestCase196 {197 return Array.Empty<TTestCase>();198 }199 }200 }201 public class AssemblyTestCollectionOrderer202 {203 [Fact]204 public static async ValueTask CanSetTestCollectionOrdererInAssemblyAttribute()205 {206 var ordererAttribute = Mocks.TestCollectionOrdererAttribute<DescendingDisplayNameCollectionOrderer>();207 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { ordererAttribute });208 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);209 await context.InitializeAsync();210 var result = context.AssemblyTestCollectionOrderer;211 Assert.IsType<DescendingDisplayNameCollectionOrderer>(result);212 }213 class DescendingDisplayNameCollectionOrderer : ITestCollectionOrderer214 {215 public IReadOnlyCollection<_ITestCollection> OrderTestCollections(IReadOnlyCollection<_ITestCollection> TestCollections) =>216 TestCollections217 .OrderByDescending(c => c.DisplayName)218 .CastOrToReadOnlyCollection();219 }220 [Fact]221 public static async ValueTask SettingUnknownTestCollectionOrderLogsDiagnosticMessage()222 {223 var spy = SpyMessageSink.Capture();224 TestContext.Current!.DiagnosticMessageSink = spy;225 var ordererAttribute = Mocks.TestCollectionOrdererAttribute("UnknownType", "UnknownAssembly");226 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { ordererAttribute });227 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);228 await context.InitializeAsync();229 var result = context.AssemblyTestCollectionOrderer;230 Assert.Null(result);231 var diagnosticMessage = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());232 Assert.Equal("Could not find type 'UnknownType' in UnknownAssembly for assembly-level test collection orderer", diagnosticMessage.Message);233 }234 [Fact]235 public static async ValueTask SettingTestCollectionOrdererWithThrowingConstructorLogsDiagnosticMessage()236 {237 var spy = SpyMessageSink.Capture();238 TestContext.Current!.DiagnosticMessageSink = spy;239 var ordererAttribute = Mocks.TestCollectionOrdererAttribute<CtorThrowingCollectionOrderer>();240 var assembly = Mocks.TestAssembly("assembly.dll", assemblyAttributes: new[] { ordererAttribute });241 await using var context = TestableXunitTestAssemblyRunnerContext.Create(assembly: assembly);242 await context.InitializeAsync();243 var result = context.AssemblyTestCollectionOrderer;244 Assert.Null(result);245 var diagnosticMessage = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());246 Assert.StartsWith($"Assembly-level test collection orderer '{typeof(CtorThrowingCollectionOrderer).FullName}' threw 'System.DivideByZeroException' during construction: Attempted to divide by zero.", diagnosticMessage.Message);247 }248 class CtorThrowingCollectionOrderer : ITestCollectionOrderer249 {250 public CtorThrowingCollectionOrderer()251 {252 throw new DivideByZeroException();253 }254 public IReadOnlyCollection<_ITestCollection> OrderTestCollections(IReadOnlyCollection<_ITestCollection> testCollections) =>255 Array.Empty<_ITestCollection>();256 }257 }258 class ClassUnderTest259 {260 [Fact]261 public void Passing() { Thread.Sleep(0); }262 [Fact]263 public void Other() { Thread.Sleep(0); }264 }265 class TestableXunitTestAssemblyRunnerContext : XunitTestAssemblyRunnerContext266 {267 TestableXunitTestAssemblyRunnerContext(268 _ITestAssembly testAssembly,269 IReadOnlyCollection<IXunitTestCase> testCases,270 _IMessageSink executionMessageSink,271 _ITestFrameworkExecutionOptions executionOptions) :272 base(testAssembly, testCases, executionMessageSink, executionOptions)273 { }274 public static TestableXunitTestAssemblyRunnerContext Create(275 _ITestAssembly? assembly = null,276 _ITestFrameworkExecutionOptions? executionOptions = null) =>277 new(278 assembly ?? Mocks.TestAssembly(),279 new[] { TestData.XunitTestCase<ClassUnderTest>("Passing") },280 SpyMessageSink.Create(),281 executionOptions ?? _TestFrameworkOptions.ForExecution()282 );283 }284}...
XunitTestFrameworkDiscovererTests.cs
Source:XunitTestFrameworkDiscovererTests.cs
...74 {75 [Fact]76 public static async ValueTask RequestsPublicAndPrivateMethodsFromType()77 {78 var typeInfo = Mocks.TypeInfo();79 var testClass = Mocks.TestClass(typeInfo);80 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();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}...
ExtensibilityPointFactoryTests.cs
Source:ExtensibilityPointFactoryTests.cs
...12 public void NoAttribute()13 {14 var spy = SpyMessageSink.Capture();15 TestContext.Current!.DiagnosticMessageSink = spy;16 var assembly = Mocks.AssemblyInfo();17 var framework = ExtensibilityPointFactory.GetTestFramework(assembly);18 Assert.IsType<XunitTestFramework>(framework);19 Assert.Empty(spy.Messages);20 }21 [Fact]22 public void Attribute_NoDiscoverer()23 {24 var spy = SpyMessageSink.Capture();25 TestContext.Current!.DiagnosticMessageSink = spy;26 var attribute = Mocks.TestFrameworkAttribute<AttributeWithoutDiscoverer>();27 var assembly = Mocks.AssemblyInfo(attributes: new[] { attribute });28 var framework = ExtensibilityPointFactory.GetTestFramework(assembly);29 Assert.IsType<XunitTestFramework>(framework);30 AssertSingleDiagnosticMessage(spy, "Assembly-level test framework attribute was not decorated with [TestFrameworkDiscoverer]");31 }32 class AttributeWithoutDiscoverer : Attribute, ITestFrameworkAttribute { }33 [Fact]34 public void Attribute_ThrowingDiscovererCtor()35 {36 CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;37 var spy = SpyMessageSink.Capture();38 TestContext.Current!.DiagnosticMessageSink = spy;39 var attribute = Mocks.TestFrameworkAttribute<AttributeWithThrowingDiscovererCtor>();40 var assembly = Mocks.AssemblyInfo(attributes: new[] { attribute });41 var factory = ExtensibilityPointFactory.GetTestFramework(assembly);42 Assert.IsType<XunitTestFramework>(factory);43 AssertSingleDiagnosticMessage(spy, "Exception thrown during test framework discoverer construction: System.DivideByZeroException: Attempted to divide by zero.");44 }45 [TestFrameworkDiscoverer(typeof(ThrowingDiscovererCtor))]46 class AttributeWithThrowingDiscovererCtor : Attribute, ITestFrameworkAttribute47 { }48 public class ThrowingDiscovererCtor : ITestFrameworkTypeDiscoverer49 {50 public ThrowingDiscovererCtor() =>51 throw new DivideByZeroException();52 public Type GetTestFrameworkType(_IAttributeInfo attribute) =>53 throw new NotImplementedException();54 }55 [Fact]56 public void Attribute_ThrowingDiscovererMethod()57 {58 CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;59 var spy = SpyMessageSink.Capture();60 TestContext.Current!.DiagnosticMessageSink = spy;61 var attribute = Mocks.TestFrameworkAttribute<AttributeWithThrowingDiscovererMethod>();62 var assembly = Mocks.AssemblyInfo(attributes: new[] { attribute });63 var framework = ExtensibilityPointFactory.GetTestFramework(assembly);64 Assert.IsType<XunitTestFramework>(framework);65 AssertSingleDiagnosticMessage(spy, "Exception thrown during test framework discoverer construction: System.DivideByZeroException: Attempted to divide by zero.");66 }67 [TestFrameworkDiscoverer(typeof(ThrowingDiscoverer))]68 class AttributeWithThrowingDiscovererMethod : Attribute, ITestFrameworkAttribute69 { }70 public class ThrowingDiscoverer : ITestFrameworkTypeDiscoverer71 {72 public Type GetTestFrameworkType(_IAttributeInfo attribute) =>73 throw new DivideByZeroException();74 }75 [Fact]76 public void Attribute_ThrowingTestFrameworkCtor()77 {78 CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;79 var spy = SpyMessageSink.Capture();80 TestContext.Current!.DiagnosticMessageSink = spy;81 var attribute = Mocks.TestFrameworkAttribute<AttributeWithThrowingTestFrameworkCtor>();82 var assembly = Mocks.AssemblyInfo(attributes: new[] { attribute });83 var framework = ExtensibilityPointFactory.GetTestFramework(assembly);84 Assert.IsType<XunitTestFramework>(framework);85 AssertSingleDiagnosticMessage(spy, "Exception thrown during test framework construction; falling back to default test framework: System.DivideByZeroException: Attempted to divide by zero.");86 }87 [TestFrameworkDiscoverer(typeof(DiscovererForThrowingTestFrameworkCtor))]88 class AttributeWithThrowingTestFrameworkCtor : Attribute, ITestFrameworkAttribute89 { }90 public class DiscovererForThrowingTestFrameworkCtor : ITestFrameworkTypeDiscoverer91 {92 public Type GetTestFrameworkType(_IAttributeInfo attribute) =>93 typeof(ThrowingTestFrameworkCtor);94 }95 public class ThrowingTestFrameworkCtor : _ITestFramework96 {97 public ThrowingTestFrameworkCtor() =>98 throw new DivideByZeroException();99 public _ISourceInformationProvider SourceInformationProvider { get; set; }100 public _ITestFrameworkDiscoverer GetDiscoverer(_IAssemblyInfo assembly) =>101 throw new NotImplementedException();102 public _ITestFrameworkExecutor GetExecutor(_IReflectionAssemblyInfo assembly) =>103 throw new NotImplementedException();104 }105 [Fact]106 public void Attribute_WithDiscoverer_NoMessageSink()107 {108 var spy = SpyMessageSink.Capture();109 TestContext.Current!.DiagnosticMessageSink = spy;110 var attribute = Mocks.TestFrameworkAttribute<AttributeWithDiscoverer>();111 var assembly = Mocks.AssemblyInfo(attributes: new[] { attribute });112 ExtensibilityPointFactory.GetTestFramework(assembly);113 Assert.Empty(spy.Messages);114 }115 [TestFrameworkDiscoverer(typeof(MyDiscoverer))]116 public class AttributeWithDiscoverer : Attribute, ITestFrameworkAttribute117 { }118 public class MyDiscoverer : ITestFrameworkTypeDiscoverer119 {120 public Type GetTestFrameworkType(_IAttributeInfo attribute) =>121 typeof(MyTestFramework);122 }123 public class MyTestFramework : _ITestFramework124 {125 public _ISourceInformationProvider? SourceInformationProvider { get; set; }126 public _ITestFrameworkDiscoverer GetDiscoverer(_IAssemblyInfo assembly) =>127 throw new NotImplementedException();128 public _ITestFrameworkExecutor GetExecutor(_IReflectionAssemblyInfo assembly) =>129 throw new NotImplementedException();130 }131 }132 public class GetXunitTestCollectionFactory : ExtensibilityPointFactoryTests133 {134 [Fact]135 public void DefaultTestCollectionFactoryIsCollectionPerClass()136 {137 var assembly = Mocks.TestAssembly();138 var result = ExtensibilityPointFactory.GetXunitTestCollectionFactory((_IAttributeInfo?)null, assembly);139 Assert.IsType<CollectionPerClassTestCollectionFactory>(result);140 }141 [Theory(DisableDiscoveryEnumeration = true)]142 [InlineData(CollectionBehavior.CollectionPerAssembly, typeof(CollectionPerAssemblyTestCollectionFactory))]143 [InlineData(CollectionBehavior.CollectionPerClass, typeof(CollectionPerClassTestCollectionFactory))]144 public void UserCanChooseFromBuiltInCollectionFactories_NonParallel(CollectionBehavior behavior, Type expectedType)145 {146 var attr = Mocks.CollectionBehaviorAttribute(behavior);147 var assembly = Mocks.TestAssembly();148 var result = ExtensibilityPointFactory.GetXunitTestCollectionFactory(attr, assembly);149 Assert.IsType(expectedType, result);150 }151 [Fact]152 public void UserCanChooseCustomCollectionFactoryWithType()153 {154 var attr = Mocks.CollectionBehaviorAttribute<MyTestCollectionFactory>();155 var assembly = Mocks.TestAssembly();156 var result = ExtensibilityPointFactory.GetXunitTestCollectionFactory(attr, assembly);157 var myFactory = Assert.IsType<MyTestCollectionFactory>(result);158 Assert.Same(assembly, myFactory.Assembly);159 }160 [Fact]161 public void UserCanChooseCustomCollectionFactoryWithTypeAndAssemblyName()162 {163 var factoryType = typeof(MyTestCollectionFactory);164 var attr = Mocks.CollectionBehaviorAttribute(factoryType.FullName!, factoryType.Assembly.FullName!);165 var assembly = Mocks.TestAssembly();166 var result = ExtensibilityPointFactory.GetXunitTestCollectionFactory(attr, assembly);167 var myFactory = Assert.IsType<MyTestCollectionFactory>(result);168 Assert.Same(assembly, myFactory.Assembly);169 }170 class MyTestCollectionFactory : IXunitTestCollectionFactory171 {172 public MyTestCollectionFactory(_ITestAssembly assembly)173 {174 Assembly = assembly;175 }176 public readonly _ITestAssembly Assembly;177 public string DisplayName =>178 "My Factory";179 public _ITestCollection Get(_ITypeInfo testClass) =>180 throw new NotImplementedException();181 }182 [Theory]183 [InlineData(184 "ExtensibilityPointFactoryTests+GetXunitTestCollectionFactory+TestCollectionFactory_NoCompatibleConstructor",185 "Could not find constructor for 'ExtensibilityPointFactoryTests+GetXunitTestCollectionFactory+TestCollectionFactory_NoCompatibleConstructor' with arguments type(s): Castle.Proxies.InterfaceProxy")]186 [InlineData(187 "ExtensibilityPointFactoryTests+GetXunitTestCollectionFactory+TestCollectionFactory_DoesNotImplementInterface",188 "Test collection factory type 'xunit.v3.core.tests, ExtensibilityPointFactoryTests+GetXunitTestCollectionFactory+TestCollectionFactory_DoesNotImplementInterface' does not implement IXunitTestCollectionFactory")]189 [InlineData(190 "ThisIsNotARealType",191 "Unable to create test collection factory type 'xunit.v3.core.tests, ThisIsNotARealType'")]192 public void IncompatibleOrInvalidTypesGetDefaultBehavior(string factoryTypeName, string expectedMessage)193 {194 var spy = SpyMessageSink.Capture();195 TestContext.Current!.DiagnosticMessageSink = spy;196#if BUILD_X86197 expectedMessage = expectedMessage.Replace("xunit.v3.core.tests", "xunit.v3.core.tests.x86");198 var attr = Mocks.CollectionBehaviorAttribute(factoryTypeName, "xunit.v3.core.tests.x86");199#else200 var attr = Mocks.CollectionBehaviorAttribute(factoryTypeName, "xunit.v3.core.tests");201#endif202 var assembly = Mocks.TestAssembly();203 var result = ExtensibilityPointFactory.GetXunitTestCollectionFactory(attr, assembly);204 AssertSingleDiagnosticMessage(spy, expectedMessage);205 }206 class TestCollectionFactory_NoCompatibleConstructor : IXunitTestCollectionFactory207 {208 public string DisplayName =>209 throw new NotImplementedException();210 public _ITestCollection Get(_ITypeInfo _) =>211 throw new NotImplementedException();212 }213 class TestCollectionFactory_DoesNotImplementInterface214 {215 public TestCollectionFactory_DoesNotImplementInterface(_IAssemblyInfo _)216 { }...
XunitTestCaseTests.cs
Source:XunitTestCaseTests.cs
...11 {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 }...
xunitTests.cs
Source:xunitTests.cs
...75 }76 [Fact]77 public void NoExplicitReporter_NoEnvironmentallyEnabledReporters_UsesDefaultReporter()78 {79 var implicitReporter = Mocks.RunnerReporter(isEnvironmentallyEnabled: false);80 var xunit = new Testable_xunit();81 xunit.AvailableReporters.Add(implicitReporter);82 var reporter = xunit.GetReporter();83 Assert.IsType<DefaultRunnerReporter>(reporter);84 }85 [Fact]86 public void ExplicitReporter_NoEnvironmentalOverride_UsesExplicitReporter()87 {88 var explicitReporter = Mocks.RunnerReporter("switch");89 var xunit = new Testable_xunit { Reporter = "switch" };90 xunit.AvailableReporters.Add(explicitReporter);91 var reporter = xunit.GetReporter();92 Assert.Same(explicitReporter, reporter);93 }94 [Fact]95 public void ExplicitReporter_WithEnvironmentalOverride_UsesEnvironmentalOverride()96 {97 var explicitReporter = Mocks.RunnerReporter("switch");98 var implicitReporter = Mocks.RunnerReporter(isEnvironmentallyEnabled: true);99 var xunit = new Testable_xunit { Reporter = "switch" };100 xunit.AvailableReporters.AddRange(new[] { explicitReporter, implicitReporter });101 var reporter = xunit.GetReporter();102 Assert.Same(implicitReporter, reporter);103 }104 [Fact]105 public void WithEnvironmentalOverride_WithEnvironmentalOverridesDisabled_UsesDefaultReporter()106 {107 var implicitReporter = Mocks.RunnerReporter(isEnvironmentallyEnabled: true);108 var xunit = new Testable_xunit { NoAutoReporters = true };109 xunit.AvailableReporters.Add(implicitReporter);110 var reporter = xunit.GetReporter();111 Assert.IsType<DefaultRunnerReporter>(reporter);112 }113 [Fact]114 public void NoExplicitReporter_SelectsFirstEnvironmentallyEnabledReporter()115 {116 var explicitReporter = Mocks.RunnerReporter("switch");117 var implicitReporter1 = Mocks.RunnerReporter(isEnvironmentallyEnabled: true);118 var implicitReporter2 = Mocks.RunnerReporter(isEnvironmentallyEnabled: true);119 var xunit = new Testable_xunit();120 xunit.AvailableReporters.AddRange(new[] { explicitReporter, implicitReporter1, implicitReporter2 });121 var reporter = xunit.GetReporter();122 Assert.Same(implicitReporter1, reporter);123 }124 [Fact]125 public void BadChosenReporter_NoAvailableReporters()126 {127 var xunit = new Testable_xunit { Reporter = "foo" };128 var reporter = xunit.GetReporter();129 Assert.Null(reporter);130 var eventArgs = Assert.IsType<BuildErrorEventArgs>(xunit.BuildEngine.Captured(x => x.LogErrorEvent(null)).Args().Single());131 Assert.Equal("Reporter value 'foo' is invalid. There are no available reporters.", eventArgs.Message);132 }133 [Fact]134 public void BadChosenReporter_WithAvailableReporters()135 {136 var xunit = new Testable_xunit { Reporter = "foo" };137 xunit.AvailableReporters.AddRange(new[] { Mocks.RunnerReporter("switch1"), Mocks.RunnerReporter("switch2") });138 var reporter = xunit.GetReporter();139 Assert.Null(reporter);140 var eventArgs = Assert.IsType<BuildErrorEventArgs>(xunit.BuildEngine.Captured(x => x.LogErrorEvent(null)).Args().Single());141 Assert.Equal("Reporter value 'foo' is invalid. Available reporters: switch1, switch2", eventArgs.Message);142 }143 }144 public class Testable_xunit : xunit145 {146 public readonly List<IRunnerReporter> AvailableReporters = new();147 public Testable_xunit()148 : this(0)149 { }150 public Testable_xunit(int exitCode)151 {...
ReflectionAbstractionExtensionsTests.cs
Source:ReflectionAbstractionExtensionsTests.cs
...6 {7 [Fact]8 public static void WhenUsingReflectionMethodInfo_ReturnsExistingMethodInfo()9 {10 var methodInfo = Mocks.MethodInfo<ToRuntimeMethod>("WhenUsingReflectionMethodInfo_ReturnsExistingMethodInfo");11 var result = methodInfo.ToRuntimeMethod();12 Assert.NotNull(result);13 Assert.Same(methodInfo.MethodInfo, result);14 }15 [Fact]16 public static void WhenUsingNonReflectionMethodInfo_MethodExists_ReturnsMethodInfo()17 {18#if BUILD_X8619 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeMethod", assemblyFileName: "xunit.v3.core.tests.x86.exe");20#else21 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeMethod", assemblyFileName: "xunit.v3.core.tests.exe");22#endif23 var methodInfo = Mocks.MethodInfo("WhenUsingNonReflectionMethodInfo_MethodExists_ReturnsMethodInfo", isStatic: true, type: typeInfo);24 var result = methodInfo.ToRuntimeMethod();25 Assert.NotNull(result);26 Assert.Same(typeof(ToRuntimeMethod).GetMethod("WhenUsingNonReflectionMethodInfo_MethodExists_ReturnsMethodInfo"), result);27 }28 [Fact]29 public static void WhenUsingNonReflectionMethodInfo_MethodDoesNotExist_ReturnsNull()30 {31 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeMethod", assemblyFileName: "xunit.v3.core.tests.exe");32 var methodInfo = Mocks.MethodInfo("UnknownMethod", isStatic: true, type: typeInfo);33 var result = methodInfo.ToRuntimeMethod();34 Assert.Null(result);35 }36 }37 public class ToRuntimeType38 {39 [Fact]40 public static void WhenUsingReflectionTypeInfo_ReturnsExistingType()41 {42 var typeInfo = Mocks.TypeInfo<ToRuntimeType>();43 var result = typeInfo.ToRuntimeType();44 Assert.NotNull(result);45 Assert.Same(typeInfo.Type, result);46 }47 [Fact]48 public static void WhenUsingNonReflectionTypeInfo_TypeExists_ReturnsType()49 {50#if BUILD_X8651 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeType", assemblyFileName: "xunit.v3.core.tests.x86.exe");52#else53 var typeInfo = Mocks.TypeInfo("ReflectionAbstractionExtensionsTests+ToRuntimeType", assemblyFileName: "xunit.v3.core.tests.exe");54#endif55 var result = typeInfo.ToRuntimeType();56 Assert.NotNull(result);57 Assert.Same(typeof(ToRuntimeType), result);58 }59 [Fact]60 public static void WhenUsingNonReflectionTypeInfo_TypeDoesNotExist_ReturnsNull()61 {62 var typeInfo = Mocks.TypeInfo("UnknownType", assemblyFileName: "xunit.v3.core.tests.exe");63 var result = typeInfo.ToRuntimeType();64 Assert.Null(result);65 }66 }67}...
DefaultTestCaseOrdererTests.cs
Source:DefaultTestCaseOrdererTests.cs
...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 {...
Mocks.cs
Source:Mocks.cs
...3using Xunit.Sdk;4namespace Xunit.v35{6 // This file contains mocks that don't belong in the other major categories.7 public static partial class Mocks8 {9 static readonly object[] EmptyObjects = new object[0];10 public static readonly _IReflectionTypeInfo TypeObject = Reflector.Wrap(typeof(object));11 public static readonly _IReflectionTypeInfo TypeString = Reflector.Wrap(typeof(string));12 public static readonly _IReflectionTypeInfo TypeVoid = Reflector.Wrap(typeof(void));13 public static IRunnerReporter RunnerReporter(14 string? runnerSwitch = null,15 string? description = null,16 bool isEnvironmentallyEnabled = false,17 _IMessageSink? messageSink = null)18 {19 description ??= "The runner reporter description";20 messageSink ??= Substitute.For<_IMessageSink, InterfaceProxy<_IMessageSink>>();21 var result = Substitute.For<IRunnerReporter, InterfaceProxy<IRunnerReporter>>();...
Mocks
Using AI Code Generation
1using Xunit;2using Xunit.Abstractions;3using Xunit.Sdk;4{5 {6 private readonly ITestOutputHelper _output;7 public Tests(ITestOutputHelper output)8 {9 _output = output;10 }11 public void Test1()12 {13 var mock = Mocks.Create<IFoo>(MockBehavior.Strict);14 mock.Setup(x => x.Bar()).Returns("bar");15 var foo = mock.Object;16 }17 }18 {19 string Bar();20 }21}
Mocks
Using AI Code Generation
1using Xunit;2using Xunit.Abstractions;3{4 {5 private readonly ITestOutputHelper _output;6 public TestClass(ITestOutputHelper output)7 {8 this._output = output;9 }10 public void TestMethod1()11 {12 var mock = Mocks.Create<IMyInterface>();13 var mockObject = mock.Object;14 mock.Setup(x => x.MyMethod()).Returns("Hello World");15 _output.WriteLine(mockObject.MyMethod());16 }17 }18}
Mocks
Using AI Code Generation
1using Xunit.v3;2using Xunit.v3;3using Xunit.v3;4using Xunit.v3;5using Xunit.v3;6using Xunit.v3;7using Xunit.v3;
Mocks
Using AI Code Generation
1using Xunit;2{3 {4 public static Mock<IFoo> Foo()5 {6 return new Mock<IFoo>();7 }8 }9}10using Xunit;11{12 {13 public void Test1()14 {15 var mock = Mocks.Foo();16 }17 }18}19Error 1 'System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()' is inaccessible due to its protection level20Error 1 'System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()' is inaccessible due to its protection level21var client = new HttpClient();22Error 1 'System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()' is inaccessible due to its protection level
Mocks
Using AI Code Generation
1using Xunit;2{3 {4 public static Mock<IFoo> Foo()5 {6 return new Mock<IFoo>();7 }8 }9}10using Xunit;11{12 {13 public void Test1()14 {15 var mock = Mocks.Foo();16 }17 }18}19Error 1 'System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()' is inaccessible due to its protection level20Error 1 'System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()' is inaccessible due to its protection level21var client = new HttpClient();22Error 1 'System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()' is inaccessible due to its protection level
Mocks
Using AI Code Generation
1using Xunit.v3;2using Xunit.v3;3using Xunit.v3;4using Xunit.v3;5using Xunit.v3;6using Xunit.v3;
Mocks
Using AI Code Generation
1var mock = new Mocks();2var mockFoo = mock.Foo();3mockFoo.Bar();4var mock = new Mock<IFoo>();5mock.Setup(m => m.Bar());6var mock = Substitute.For<IFoo>();7mock.Bar();8var mock = MockRepos3 orypGenerateMock<IFoo>();9mock.Bar();10aar mock = Isolate.Fake.Instance<IFoo>();11mock.Bar();12var mock = Isolate.Fake.Instance<IFoo>();13mock.Bar();14var mock = Isolate.Fake.Instance<IFoo>();15mock.Bar();16var mock = Isolate.Fake.Instance<IFoo>();17mock.Bar();18var mock = Isolate.Fake.Instance<IFoo>();19mock.Bar();20var mock = Isolate.Fake.Instance<IFoo>();21mock.Bar();22var mock = Isolate.Fake.Instance<IFoo>();23mock.Bar();24var mock = Isolate.Fake.Instance<IFoo>();25mock.Bar();26var mock = Isolate.Fake.Instance<IFoo>();27mock.Bar();28var mock = Isolate.Fake.Instance<IFoo>();29mock.Bar();30var mock = Isolate.Fake.Instance<IFoo>();31mock.Bar();32var mock = Isolate.Fake.Instance<using Xunit.v3;33using Xunit.v3;
Mocks
Using AI Code Generation
1var mock = new Mocks();2var mock1 = mock.Create<ICustomer>();3var mock2 = mock.Create<ICustomer>();4var mock3 = mock.Create<ICustomer>();5var mock4 = mock.Create<ICustomer>();6var mock5 = mock.Create<ICustomer>();7var mock6 = mock.Create<ICustomer>();8var mock7 = mock.Create<ICustomer>();9var mock8 = mock.Create<ICustomer>();10var mock9 = mock.Create<ICustomer>();11var mock10 = mock.Create<ICustomer>();12var mock11 = mock.Create<ICustomer>();13var mock12 = mock.Create<ICustomer>();14var mock13 = mock.Create<ICustomer>();15var mock14 = mock.Create<ICustomer>();16var mock15 = mock.Create<ICustomer>();17var mock16 = mock.Create<ICustomer>();18var mock17 = mock.Create<ICustomer>();19var mock18 = mock.Create<ICustomer>();20var mock19 = mock.Create<ICustomer>();21var mock20 = mock.Create<ICustomer>();22var mock21 = mock.Create<ICustomer>();23var mock22 = mock.Create<ICustomer>();24var mock23 = mock.Create<ICustomer>();25var mock24 = mock.Create<ICustomer>();26var mock25 = mock.Create<ICustomer>();27var mock26 = mock.Create<ICustomer>();28var mock27 = mock.Create<ICustomer>();29var mock28 = mock.Create<ICustomer>();30var mock29 = mock.Create<ICustomer>();31var mock30 = mock.Create<ICustomer>();32var mock31 = mock.Create<ICustomer>();33var mock32 = mock.Create<ICustomer>();34var mock33 = mock.Create<ICustomer>();35var mock34 = mock.Create<ICustomer>();36var mock35 = mock.Create<ICustomer>();37var mock36 = mock.Create<ICustomer>();38var mock37 = mock.Create<ICustomer>();39var mock38 = mock.Create<ICustomer>();40var mock39 = mock.Create<ICustomer>();41var mock40 = mock.Create<ICustomer>();42var mock41 = mock.Create<ICustomer>();43var mock42 = mock.Create<ICustomer>();44var mock43 = mock.Create<ICustomer>();45var mock44 = mock.Create<ICustomer>();46var mock45 = mock.Create<ICustomer>();47var mock46 = mock.Create<ICustomer>();48var mock47 = mock.Create<ICustomer>();49var mock48 = mock.Create<ICustomer>();50var mock49 = mock.Create<ICustomer>();
Mocks
Using AI Code Generation
1var mock = new Mocks();2var mockFoo = mock.Foo();3mockFoo.Bar();4var mock = new Mock<IFoo>();5mock.Setup(m => m.Bar());6var mock = Substitute.For<IFoo>();7mock.Bar();8var mock = MockRepository.GenerateMock<IFoo>();9mock.Bar();10var mock = Isolate.Fake.Instance<IFoo>();11mock.Bar();12var mock = Isolate.Fake.Instance<IFoo>();13mock.Bar();14var mock = Isolate.Fake.Instance<IFoo>();15mock.Bar();16var mock = Isolate.Fake.Instance<IFoo>();17mock.Bar();18var mock = Isolate.Fake.Instance<IFoo>();19mock.Bar();20var mock = Isolate.Fake.Instance<IFoo>();21mock.Bar();22var mock = Isolate.Fake.Instance<IFoo>();23mock.Bar();24var mock = Isolate.Fake.Instance<IFoo>();25mock.Bar();26var mock = Isolate.Fake.Instance<IFoo>();27mock.Bar();28var mock = Isolate.Fake.Instance<IFoo>();29mock.Bar();30var mock = Isolate.Fake.Instance<IFoo>();31mock.Bar();
Mocks
Using AI Code Generation
1using Xunit;2using Xunit.Abstractions;3using Xunit.Sdk;4{5 {6 public Mocks(ITestOutputHelper output)7 {8 var sink = new TestOutputHelperMessageSink(output);9 XunitContext.Context = new XunitContext(sink);10 }11 public void Dispose()12 {13 XunitContext.Context = null;14 }15 }16}17using Xunit;18using Xunit.Abstractions;19{20 {21 public void Test()22 {23 using (new Mocks(_output))24 {25 }26 }27 }28}
Mocks
Using AI Code Generation
1{2 {3 public static T Of<T>() where T : class, new()4 {5 return new T();6 }7 }8}9{10 {11 public static T Of<T>() where T : class, new()12 {13 return new T();14 }15 }16}17{18 {19 public static T Of<T>() where T : class, new()20 {21 return new T();22 }23 }24}25{26 {27 public static T Of<T>() where T : class, new()28 {29 return new T();30 }31 }32}33{34 {35 public static T Of<T>() where T : class, new()36 {37 return new T();38 }39 }40}41{42 {43 public static T Of<T>() where T : class, new()44 {45 return new T();46 }47 }48}49{50 {51 public static T Of<T>() where T : class,
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!