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

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

XunitTestAssemblyRunnerContextTests.cs

Source:XunitTestAssemblyRunnerContextTests.cs Github

copy

Full Screen

...7using Xunit.Internal;8using Xunit.Runner.Common;9using Xunit.Sdk;10using Xunit.v3;11public class XunitTestAssemblyRunnerContextTests12{13 public class TestFrameworkDisplayName14 {15 [Fact]16 public static async ValueTask IsXunit()17 {18 await using var context = TestableXunitTestAssemblyRunnerContext.Create();19 await context.InitializeAsync();20 var result = context.TestFrameworkDisplayName;21 Assert.StartsWith("xUnit.net v3 ", result);22 }23 }24 public class TestFrameworkEnvironment25 {26 [Fact]27 public static async ValueTask Default()28 {29 await using var context = TestableXunitTestAssemblyRunnerContext.Create();30 await context.InitializeAsync();31 var result = context.TestFrameworkEnvironment;32 Assert.EndsWith($"[collection-per-class, parallel ({Environment.ProcessorCount} threads)]", result);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}...

Full Screen

Full Screen

XunitTestFrameworkDiscovererTests.cs

Source:XunitTestFrameworkDiscovererTests.cs Github

copy

Full Screen

...6using Xunit;7using Xunit.Runner.Common;8using Xunit.Sdk;9using Xunit.v3;10public class XunitTestFrameworkDiscovererTests11{12 public class Construction13 {14 [Fact]15 public static void GuardClause()16 {17 Assert.Throws<ArgumentNullException>("assemblyInfo", () => new XunitTestFrameworkDiscoverer(assemblyInfo: null!, configFileName: null));18 }19 }20 public class CreateTestClass21 {22 class ClassWithNoCollection23 {24 [Fact]25 public static void TestMethod() { }26 }27 [Fact]28 public static async void DefaultTestCollection()29 {30 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();31 var type = Reflector.Wrap(typeof(ClassWithNoCollection));32 var testClass = await discoverer.CreateTestClass(type);33 Assert.NotNull(testClass.TestCollection);34 Assert.Equal("Test collection for XunitTestFrameworkDiscovererTests+CreateTestClass+ClassWithNoCollection", testClass.TestCollection.DisplayName);35 Assert.Null(testClass.TestCollection.CollectionDefinition);36 }37 [Collection("This a collection without declaration")]38 class ClassWithUndeclaredCollection39 {40 [Fact]41 public static void TestMethod() { }42 }43 [Fact]44 public static async void UndeclaredTestCollection()45 {46 var discoverer = TestableXunitTestFrameworkDiscoverer.Create();47 var type = Reflector.Wrap(typeof(ClassWithUndeclaredCollection));48 var testClass = await discoverer.CreateTestClass(type);49 Assert.NotNull(testClass.TestCollection);50 Assert.Equal("This a collection without declaration", testClass.TestCollection.DisplayName);51 Assert.Null(testClass.TestCollection.CollectionDefinition);52 }53 [CollectionDefinition("This a defined collection")]54 public class DeclaredCollection { }55 [Collection("This a defined collection")]56 class ClassWithDefinedCollection57 {58 [Fact]59 public static void TestMethod() { }60 }61 [Fact]62 public static async void DefinedTestCollection()63 {64 var type = Reflector.Wrap(typeof(ClassWithDefinedCollection));65 var discoverer = TestableXunitTestFrameworkDiscoverer.Create(type.Assembly);66 var testClass = await discoverer.CreateTestClass(type);67 Assert.NotNull(testClass.TestCollection);68 Assert.Equal("This a defined collection", testClass.TestCollection.DisplayName);69 Assert.NotNull(testClass.TestCollection.CollectionDefinition);70 Assert.Equal("XunitTestFrameworkDiscovererTests+CreateTestClass+DeclaredCollection", testClass.TestCollection.CollectionDefinition.Name);71 }72 }73 public class FindTestsForType74 {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}...

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

ExtensibilityPointFactoryTests.cs

Source:ExtensibilityPointFactoryTests.cs Github

copy

Full Screen

...3using Xunit;4using Xunit.Runner.Common;5using Xunit.Sdk;6using Xunit.v3;7public class ExtensibilityPointFactoryTests8{9 public class GetTestFramework : ExtensibilityPointFactoryTests10 {11 [Fact]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 { }217 }218 }219 void AssertSingleDiagnosticMessage(SpyMessageSink spy, string expectedMessage)220 {221 var message = Assert.Single(spy.Messages);222 var diagnosticMessage = Assert.IsAssignableFrom<_DiagnosticMessage>(message);223 Assert.StartsWith(expectedMessage, diagnosticMessage.Message);224 }225}...

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

...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,...

Full Screen

Full Screen

FactDiscovererTests.cs

Source:FactDiscovererTests.cs Github

copy

Full Screen

...4using Xunit;5using Xunit.Runner.Common;6using Xunit.Sdk;7using Xunit.v3;8public class FactDiscovererTests9{10 readonly ExceptionAggregator aggregator;11 readonly CancellationTokenSource cancellationTokenSource;12 readonly _IReflectionAttributeInfo factAttribute;13 readonly SpyMessageBus messageBus;14 readonly _ITestFrameworkDiscoveryOptions options;15 public FactDiscovererTests()16 {17 aggregator = new ExceptionAggregator();18 cancellationTokenSource = new CancellationTokenSource();19 factAttribute = Mocks.FactAttribute();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() { }61 [Fact]62 public void FactWithParameters(int x) { }63 [Fact]64 public void GenericFact<T>() { }65 }66}...

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]45 public void Test6() { }46 }47}...

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1var mock = new Xunit.v3.Mocks();2mock.Test();3var mock = new Xunit.v3.Mocks();4mock.Test();5var mock = new Xunit.v3.Mocks();6mock.Test();7var mock = new Xunit.v3.Mocks();8mock.Test();9var mock = new Xunit.v3.Mocks();10mock.Test();11var mock = new Xunit.v3.Mocks();12mock.Test();13var mock = new Xunit.v3.Mocks();14mock.Test();15var mock = new Xunit.v3.Mocks();16mock.Test();17var mock = new Xunit.v3.Mocks();18mock.Test();19var mock = new Xunit.v3.Mocks();20mock.Test();21var mock = new Xunit.v3.Mocks();22mock.Test();23var mock = new Xunit.v3.Mocks();24mock.Test();25var mock = new Xunit.v3.Mocks();26mock.Test();27var mock = new Xunit.v3.Mocks();28mock.Test();29var mock = new Xunit.v3.Mocks();30mock.Test();

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2{3 {4 public void TestMethod1()5 {6 var mock = new Xunit.v3.Mocks.Test();7 mock.Test("test");8 }9 }10}11using Xunit.v3.Mocks;12{13 {14 public void TestMethod1()15 {16 var mock = new Xunit.v3.Mocks.Test();17 mock.Test("test");18 }19 }20}

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3;3{4 public void Test()5 {6 var mock = new Xunit.v3.Mocks();7 mock.Test("TestName", "TestDisplayName", "TestAssemblyUniqueName", "TestAssemblyPath", "TestAssemblyConfigFileName", "TestCollectionUniqueName", "TestClass", "TestMethod", "TestSkipReason", "TestSourceFilePath", "TestSourceLineNumber", "TestTraits", "TestMessages", "TestOutput");8 }9}

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3;3{4 public void TestMethod()5 {6 var mock = new Xunit.v3.Mocks();7 mock.Test("Test");8 }9}10using Xunit;11using Xunit.v3;12{13 {14 public void Test(string name)15 {16 Console.WriteLine("Test with name {0} is running", name);17 }18 }19}20using Xunit;21using Xunit.v3;22{23 {24 public void Test(string name)25 {26 Console.WriteLine("Test with name {0} is running", name);27 }28 }29 {30 static void Main(string[] args)31 {32 var mock = new Xunit.v3.Mocks();33 mock.Test("Test");34 }35 }36}

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3;3{4 public void TestMethod()5 {6 var mock = new Xunit.v3.Mocks();7 mock.Test("TestMessage");8 }9}10using Xunit;11using Xunit.v3;12{13 public void TestMethod()14 {15 var mock = new Xunit.v3.Mocks();16 mock.Test("TestMessage");17 }18}19The type or namespace name 'Mocks' does not exist in the namespace 'Xunit.v3' (are you missing an assembly reference?)20using Xunit;21using Xunit.v3;22{23 public void TestMethod()24 {25 var mock = new Xunit.v3.Mocks();26 Xunit.v3.Mocks.Test("TestMessage");27 }28}29using Xunit;30using Xunit.v3;31{32 public void TestMethod()33 {34 Xunit.v3.Mocks.Test("TestMessage");35 }36}37using Xunit;38using Xunit.v3;39{40 public void TestMethod()41 {42 Xunit.v3.Mocks.Test("TestMessage");43 }44}45using Xunit;46using Xunit.v3;47{48 public void TestMethod()49 {

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2using Xunit.v3.Mocks;3using Xunit.v3;4using Xunit.v3;5public void TestMethod1()6{7 var mock = new Xunit.v3.Mocks();8 var mockTest = mock.Test("test");9 var mockTestCase = mock.TestCase("test case", "test class", "test method");10 var mockTestResult = mock.TestResult("test result");11 mockTest.TestCase = mockTestCase;12 mockTestResult.TestCase = mockTestCase;13 mockTestResult.Test = mockTest;14 mockTestResult.Output = "output";15 mockTestResult.Messages.Add(new Xunit.v3.Message());

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1{2 {3 public void Test()4 {5 var mock = new Xunit.v3.Mocks.ClassData();6 mock.Test(new Xunit.v3.Mocks.TestCase());7 }8 }9}10{11 {12 public void Test()13 {14 var mock = new Xunit.v3.Mocks.ClassData();15 mock.Test(new Xunit.v3.Mocks.TestCase());16 }17 }18}19var assembly = Assembly.GetExecutingAssembly();20var name = new AssemblyName(assembly.FullName);21var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);22var moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name, name.Name + ".dll");23var typeBuilder = moduleBuilder.DefineType("MyNamespace.MyClass", TypeAttributes.Public);24I tried to create the type with CreateType() but it does not work. How can I create a namespace and a class in the current assembly?25var assembly = Assembly.GetExecutingAssembly();26var name = new AssemblyName(assembly.FullName);27var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);28var moduleBuilder = assemblyBuilder.DefineDynamicModule(name.Name, name.Name + ".dll");29var typeBuilder = moduleBuilder.DefineType("MyNamespace.MyClass", TypeAttributes.Public);

Full Screen

Full Screen

Test

Using AI Code Generation

copy

Full Screen

1public void Test()2{3 Xunit.v3.Mocks.Test("Hello", "Hello");4}5public void Test()6{7 Xunit.v3.Mocks.Test("Hello", "Hello");8}9public void Test()10{11 Xunit.v3.Mocks.Test("Hello", "Hello");12}13public void Test()14{15 Xunit.v3.Mocks.Test("Hello", "Hello");16}17public void Test()18{19 Xunit.v3.Mocks.Test("Hello", "Hello");20}21public void Test()22{23 Xunit.v3.Mocks.Test("Hello", "Hello");24}25public void Test()26{27 Xunit.v3.Mocks.Test("Hello", "Hello");28}29public void Test()30{31 Xunit.v3.Mocks.Test("Hello", "Hello");32}33public void Test()34{35 Xunit.v3.Mocks.Test("Hello", "Hello");36}37public void Test()38{39 Xunit.v3.Mocks.Test("Hello", "Hello");40}

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