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

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

TheoryDiscovererTests.cs

Source:TheoryDiscovererTests.cs Github

copy

Full Screen

...67 public async void DiscoveryOptions_PreEnumerateTheoriesSetToTrue_YieldsTestCasePerDataRow()68 {69 discoveryOptions.SetPreEnumerateTheories(true);70 var discoverer = new TheoryDiscoverer();71 var testMethod = Mocks.TestMethod<MultipleDataClass>(nameof(MultipleDataClass.TheoryMethod));72 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();73 var testCases = (await discoverer.Discover(discoveryOptions, testMethod, factAttribute)).ToList();74 Assert.Collection(75 testCases.Select(tc => tc.TestCaseDisplayName).OrderBy(x => x),76 displayName => Assert.Equal($"{typeof(MultipleDataClass).FullName}.{nameof(MultipleDataClass.TheoryMethod)}(x: 2112)", displayName),77 displayName => Assert.Equal($"{typeof(MultipleDataClass).FullName}.{nameof(MultipleDataClass.TheoryMethod)}(x: 42)", displayName)78 );79 }80 [Fact]81 public async void DiscoveryOptions_PreEnumerateTheoriesSetToFalse_YieldsSingleTestCase()82 {83 discoveryOptions.SetPreEnumerateTheories(false);84 var discoverer = new TheoryDiscoverer();85 var testMethod = Mocks.TestMethod<MultipleDataClass>(nameof(MultipleDataClass.TheoryMethod));86 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();87 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);88 var testCase = Assert.Single(testCases);89 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);90 Assert.Equal($"{typeof(MultipleDataClass).FullName}.{nameof(MultipleDataClass.TheoryMethod)}", testCase.TestCaseDisplayName);91 }92 class MultipleDataAttribute : DataAttribute93 {94 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod) =>95 new(96 new[]97 {98 new TheoryDataRow(42),99 new TheoryDataRow(2112)100 }101 );102 }103 class MultipleDataClass104 {105 [Theory, MultipleDataAttribute]106 public void TheoryMethod(int x) { }107 }108 [Fact]109 public async void DiscoveryOptions_PreEnumerateTheoriesSetToTrueWithSkipOnData_YieldsSkippedTestCasePerDataRow()110 {111 discoveryOptions.SetPreEnumerateTheories(true);112 var discoverer = new TheoryDiscoverer();113 var testMethod = Mocks.TestMethod<MultipleDataClassSkipped>(nameof(MultipleDataClassSkipped.TheoryMethod));114 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();115 var testCases = (await discoverer.Discover(discoveryOptions, testMethod, factAttribute)).ToList();116 Assert.Collection(117 testCases.OrderBy(tc => tc.TestCaseDisplayName),118 testCase =>119 {120 Assert.Equal($"{typeof(MultipleDataClassSkipped).FullName}.{nameof(MultipleDataClassSkipped.TheoryMethod)}(x: 2112)", testCase.TestCaseDisplayName);121 Assert.Equal("Skip this attribute", testCase.SkipReason);122 },123 testCase =>124 {125 Assert.Equal($"{typeof(MultipleDataClassSkipped).FullName}.{nameof(MultipleDataClassSkipped.TheoryMethod)}(x: 42)", testCase.TestCaseDisplayName);126 Assert.Equal("Skip this attribute", testCase.SkipReason);127 }128 );129 }130 class MultipleDataClassSkipped131 {132 [Theory, MultipleData(Skip = "Skip this attribute")]133 public void TheoryMethod(int x) { }134 }135 [Fact]136 public async void ThrowingData()137 {138 var spy = SpyMessageSink.Capture();139 TestContext.Current!.DiagnosticMessageSink = spy;140 var discoverer = new TheoryDiscoverer();141 var testMethod = Mocks.TestMethod<ThrowingDataClass>("TheoryWithMisbehavingData");142 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();143 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);144 var testCase = Assert.Single(testCases);145 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);146 Assert.Equal($"{typeof(ThrowingDataClass).FullName}.{nameof(ThrowingDataClass.TheoryWithMisbehavingData)}", testCase.TestCaseDisplayName);147 var diagnostic = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());148 Assert.StartsWith($"Exception thrown during theory discovery on '{typeof(ThrowingDataClass).FullName}.{nameof(ThrowingDataClass.TheoryWithMisbehavingData)}'; falling back to single test case.{Environment.NewLine}System.DivideByZeroException: Attempted to divide by zero.", diagnostic.Message);149 }150 class ThrowingDataAttribute : DataAttribute151 {152 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo method)153 {154 throw new DivideByZeroException();155 }156 }157 class ThrowingDataClass158 {159 [Theory, ThrowingData]160 public void TheoryWithMisbehavingData(string a) { }161 }162 [Fact]163 public async void DataDiscovererReturningNullYieldsSingleTheoryTestCase()164 {165 var spy = SpyMessageSink.Capture();166 TestContext.Current!.DiagnosticMessageSink = spy;167 var discoverer = new TheoryDiscoverer();168 var theoryAttribute = Mocks.TheoryAttribute();169 var dataAttribute = Mocks.DataAttribute();170 var testMethod = Mocks.TestMethod("MockTheoryType", "MockTheoryMethod", methodAttributes: new[] { theoryAttribute, dataAttribute });171 var testCases = await discoverer.Discover(discoveryOptions, testMethod, theoryAttribute);172 var testCase = Assert.Single(testCases);173 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);174 Assert.Equal("MockTheoryType.MockTheoryMethod", testCase.TestCaseDisplayName);175 var diagnostic = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());176 Assert.StartsWith($"Exception thrown during theory discovery on 'MockTheoryType.MockTheoryMethod'; falling back to single test case.{Environment.NewLine}System.InvalidOperationException: Sequence contains no elements", diagnostic.Message);177 }178 [Fact]179 public async void NonSerializableDataYieldsSingleTheoryTestCase()180 {181 var spy = SpyMessageSink.Capture();182 TestContext.Current!.DiagnosticMessageSink = spy;183 var discoverer = new TheoryDiscoverer();184 var testMethod = Mocks.TestMethod<NonSerializableDataClass>(nameof(NonSerializableDataClass.TheoryMethod));185 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();186 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);187 var testCase = Assert.Single(testCases);188 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);189 Assert.Equal($"{typeof(NonSerializableDataClass).FullName}.{nameof(NonSerializableDataClass.TheoryMethod)}", testCase.TestCaseDisplayName);190 var diagnostic = Assert.Single(spy.Messages.OfType<_DiagnosticMessage>());191 Assert.Equal($"Non-serializable data (one or more of: '{typeof(NonSerializableDataAttribute).FullName}') found for '{typeof(NonSerializableDataClass).FullName}.{nameof(NonSerializableDataClass.TheoryMethod)}'; falling back to single test case.", diagnostic.Message);192 }193 class NonSerializableDataAttribute : DataAttribute194 {195 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo method) =>196 new(197 new[]198 {199 new TheoryDataRow(42),200 new TheoryDataRow(new NonSerializableDataAttribute())201 }202 );203 }204 class NonSerializableDataClass205 {206 [Theory, NonSerializableData]207 public void TheoryMethod(object a) { }208 }209 [Fact]210 public async void NoSuchDataDiscoverer_ThrowsInvalidOperationException()211 {212 var results = await RunAsync<_TestFailed>(typeof(NoSuchDataDiscovererClass));213 var failure = Assert.Single(results);214 Assert.Equal(typeof(InvalidOperationException).FullName, failure.ExceptionTypes.Single());215 Assert.Equal($"Data discoverer specified for {typeof(NoSuchDataDiscovererAttribute).FullName} on {typeof(NoSuchDataDiscovererClass).FullName}.{nameof(NoSuchDataDiscovererClass.Test)} does not exist.", failure.Messages.Single());216 }217 class NoSuchDataDiscovererClass218 {219 [Theory]220 [NoSuchDataDiscoverer]221 public void Test() { }222 }223 [DataDiscoverer("Foo.Blah.ThingDiscoverer", "invalid_assembly_name")]224 public class NoSuchDataDiscovererAttribute : DataAttribute225 {226 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod)227 {228 throw new NotImplementedException();229 }230 }231 [Fact]232 public async void NotADataDiscoverer_ThrowsInvalidOperationException()233 {234 var results = await RunAsync<_TestFailed>(typeof(NotADataDiscovererClass));235 var failure = Assert.Single(results);236 Assert.Equal("System.InvalidOperationException", failure.ExceptionTypes.Single());237 Assert.Equal($"Data discoverer specified for {typeof(NotADataDiscovererAttribute).FullName} on {typeof(NotADataDiscovererClass).FullName}.{nameof(NotADataDiscovererClass.Test)} does not implement IDataDiscoverer.", failure.Messages.Single());238 }239 class NotADataDiscovererClass240 {241 [Theory]242 [NotADataDiscoverer]243 public void Test() { }244 }245 [DataDiscoverer(typeof(TheoryDiscovererTests))]246 public class NotADataDiscovererAttribute : DataAttribute247 {248 public override ValueTask<IReadOnlyCollection<ITheoryDataRow>?> GetData(MethodInfo testMethod)249 {250 throw new NotImplementedException();251 }252 }253 [Fact]254 public async void DiscoveryDisabledOnTheoryAttribute_YieldsSingleTheoryTestCase()255 {256 var discoverer = new TheoryDiscoverer();257 var testMethod = Mocks.TestMethod<NonDiscoveryOnTheoryAttribute>(nameof(NonDiscoveryOnTheoryAttribute.TheoryMethod));258 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();259 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);260 var testCase = Assert.Single(testCases);261 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);262 Assert.Equal($"{typeof(NonDiscoveryOnTheoryAttribute).FullName}.{nameof(NonDiscoveryOnTheoryAttribute.TheoryMethod)}", testCase.TestCaseDisplayName);263 }264 class NonDiscoveryOnTheoryAttribute265 {266 public static IEnumerable<object[]> foo { get { return Enumerable.Empty<object[]>(); } }267 public static IEnumerable<object[]> bar { get { return Enumerable.Empty<object[]>(); } }268 [Theory(DisableDiscoveryEnumeration = true)]269 [MemberData(nameof(foo))]270 [MemberData(nameof(bar))]271 public static void TheoryMethod(int x) { }272 }273 [Fact]274 public async void DiscoveryDisabledOnMemberData_YieldsSingleTheoryTestCase()275 {276 var discoverer = new TheoryDiscoverer();277 var testMethod = Mocks.TestMethod<NonDiscoveryEnumeratedData>(nameof(NonDiscoveryEnumeratedData.TheoryMethod));278 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();279 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);280 var testCase = Assert.Single(testCases);281 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);282 Assert.Equal($"{typeof(NonDiscoveryEnumeratedData).FullName}.{nameof(NonDiscoveryEnumeratedData.TheoryMethod)}", testCase.TestCaseDisplayName);283 }284 class NonDiscoveryEnumeratedData285 {286 public static IEnumerable<object[]> foo { get { return Enumerable.Empty<object[]>(); } }287 public static IEnumerable<object[]> bar { get { return Enumerable.Empty<object[]>(); } }288 [Theory]289 [MemberData(nameof(foo), DisableDiscoveryEnumeration = true)]290 [MemberData(nameof(bar), DisableDiscoveryEnumeration = true)]291 public static void TheoryMethod(int x) { }292 }293 [Fact]294 public async void MixedDiscoveryEnumerationOnMemberData_YieldsSingleTheoryTestCase()295 {296 var discoverer = new TheoryDiscoverer();297 var testMethod = Mocks.TestMethod<MixedDiscoveryEnumeratedData>(nameof(MixedDiscoveryEnumeratedData.TheoryMethod));298 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();299 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);300 var testCase = Assert.Single(testCases);301 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);302 Assert.Equal($"{typeof(MixedDiscoveryEnumeratedData).FullName}.{nameof(MixedDiscoveryEnumeratedData.TheoryMethod)}", testCase.TestCaseDisplayName);303 }304 class MixedDiscoveryEnumeratedData305 {306 public static IEnumerable<object[]> foo { get { return Enumerable.Empty<object[]>(); } }307 public static IEnumerable<object[]> bar { get { return Enumerable.Empty<object[]>(); } }308 [Theory]309 [MemberData(nameof(foo), DisableDiscoveryEnumeration = false)]310 [MemberData(nameof(bar), DisableDiscoveryEnumeration = true)]311 public static void TheoryMethod(int x) { }312 }313 [Fact]314 public async void SkippedTheoryWithNoData()315 {316 var msgs = await RunAsync(typeof(SkippedWithNoData));317 var skip = Assert.Single(msgs.OfType<_TestSkipped>());318 var skipStarting = Assert.Single(msgs.OfType<_TestStarting>().Where(s => s.TestUniqueID == skip.TestUniqueID));319 Assert.Equal($"{typeof(SkippedWithNoData).FullName}.{nameof(SkippedWithNoData.TestMethod)}", skipStarting.TestDisplayName);320 Assert.Equal("I have no data", skip.Reason);321 }322 class SkippedWithNoData323 {324 [Theory(Skip = "I have no data")]325 public void TestMethod(int value) { }326 }327 [Fact]328 public async void SkippedTheoryWithData()329 {330 var msgs = await RunAsync(typeof(SkippedWithData));331 var skip = Assert.Single(msgs.OfType<_TestSkipped>());332 var skipStarting = Assert.Single(msgs.OfType<_TestStarting>().Where(s => s.TestUniqueID == skip.TestUniqueID));333 Assert.Equal($"{typeof(SkippedWithData).FullName}.{nameof(SkippedWithData.TestMethod)}", skipStarting.TestDisplayName);334 Assert.Equal("I have data", skip.Reason);335 }336 class SkippedWithData337 {338 [Theory(Skip = "I have data")]339 [InlineData(42)]340 [InlineData(2112)]341 public void TestMethod(int value) { }342 }343 [Fact]344 public async void TheoryWithSerializableInputDataThatIsntSerializableAfterConversion_YieldsSingleTheoryTestCase()345 {346 TestContext.Current!.DiagnosticMessageSink = SpyMessageSink.Capture();347 var discoverer = new TheoryDiscoverer();348 var testMethod = Mocks.TestMethod<ClassWithExplicitConvertedData>(nameof(ClassWithExplicitConvertedData.ParameterDeclaredExplicitConversion));349 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();350 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);351 var testCase = Assert.Single(testCases);352 Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);353 Assert.Equal($"{typeof(ClassWithExplicitConvertedData).FullName}.{nameof(ClassWithExplicitConvertedData.ParameterDeclaredExplicitConversion)}", testCase.TestCaseDisplayName);354 }355 class ClassWithExplicitConvertedData356 {357 // Explicit conversion defined on the parameter's type358 [Theory]359 [InlineData("abc")]360 public void ParameterDeclaredExplicitConversion(Explicit e)361 {362 Assert.Equal("abc", e.Value);363 }364 public class Explicit365 {366 public string? Value { get; set; }367 public static explicit operator Explicit(string value)368 {369 return new Explicit() { Value = value };370 }371 public static explicit operator string?(Explicit e)372 {373 return e.Value;374 }375 }376 }377 class ClassWithSkippedTheoryDataRows378 {379 public static IEnumerable<ITheoryDataRow> Data =>380 new[]381 {382 new TheoryDataRow(42) { Skip = "Do not run this test" },383 new TheoryDataRow(2112),384 };385 [Theory]386 [MemberData(nameof(Data))]387 public void TestWithSomeSkippedTheoryRows(int x)388 {389 Assert.Equal(96, x);390 }391 }392 [Fact]393 public async void CanSkipFromTheoryDataRow_Preenumerated()394 {395 var discoverer = new TheoryDiscoverer();396 var testMethod = Mocks.TestMethod<ClassWithSkippedTheoryDataRows>(nameof(ClassWithSkippedTheoryDataRows.TestWithSomeSkippedTheoryRows));397 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();398 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);399 Assert.Collection(400 testCases.OrderBy(tc => tc.TestCaseDisplayName),401 testCase =>402 {403 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);404 Assert.Equal($"{typeof(ClassWithSkippedTheoryDataRows).FullName}.{nameof(ClassWithSkippedTheoryDataRows.TestWithSomeSkippedTheoryRows)}(x: 2112)", testCase.TestCaseDisplayName);405 Assert.Null(testCase.SkipReason);406 },407 testCase =>408 {409 Assert.IsType<XunitSkippedDataRowTestCase>(testCase);410 Assert.Equal($"{typeof(ClassWithSkippedTheoryDataRows).FullName}.{nameof(ClassWithSkippedTheoryDataRows.TestWithSomeSkippedTheoryRows)}(x: 42)", testCase.TestCaseDisplayName);411 Assert.Equal("Do not run this test", testCase.SkipReason);412 }413 );414 }415 [Trait("Class", "ClassWithTraitsOnTheoryDataRows")]416 class ClassWithTraitsOnTheoryDataRows417 {418 public static IEnumerable<ITheoryDataRow> Data =>419 new[]420 {421 new TheoryDataRow(42).WithTrait("Number", "42"),422 new TheoryDataRow(2112) { Skip = "I am skipped" }.WithTrait("Number", "2112"),423 };424 [Theory]425 [Trait("Theory", "TestWithTraits")]426 [MemberData(nameof(Data))]427 public void TestWithTraits(int x)428 {429 Assert.Equal(96, x);430 }431 }432 [Fact]433 public async void CanAddTraitsFromTheoryDataRow_Preenumerated()434 {435 var discoverer = new TheoryDiscoverer();436 var testMethod = Mocks.TestMethod<ClassWithTraitsOnTheoryDataRows>(nameof(ClassWithTraitsOnTheoryDataRows.TestWithTraits));437 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();438 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);439 Assert.Collection(440 testCases.OrderBy(tc => tc.TestCaseDisplayName),441 testCase =>442 {443 Assert.IsType<XunitSkippedDataRowTestCase>(testCase);444 Assert.Equal($"{typeof(ClassWithTraitsOnTheoryDataRows).FullName}.{nameof(ClassWithTraitsOnTheoryDataRows.TestWithTraits)}(x: 2112)", testCase.TestCaseDisplayName);445 Assert.Collection(446 testCase.Traits.OrderBy(kvp => kvp.Key),447 kvp => // Assembly level trait448 {449 Assert.Equal("Assembly", kvp.Key);450 var traitValue = Assert.Single(kvp.Value);451 Assert.Equal("Trait", traitValue);452 },453 kvp => // Class level trait454 {455 Assert.Equal("Class", kvp.Key);456 var traitValue = Assert.Single(kvp.Value);457 Assert.Equal("ClassWithTraitsOnTheoryDataRows", traitValue);458 },459 kvp => // Row level trait460 {461 Assert.Equal("Number", kvp.Key);462 var traitValue = Assert.Single(kvp.Value);463 Assert.Equal("2112", traitValue);464 },465 kvp => // Theory level trait466 {467 Assert.Equal("Theory", kvp.Key);468 var traitValue = Assert.Single(kvp.Value);469 Assert.Equal("TestWithTraits", traitValue);470 }471 );472 },473 testCase =>474 {475 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);476 Assert.Equal($"{typeof(ClassWithTraitsOnTheoryDataRows).FullName}.{nameof(ClassWithTraitsOnTheoryDataRows.TestWithTraits)}(x: 42)", testCase.TestCaseDisplayName);477 Assert.Collection(478 testCase.Traits.OrderBy(kvp => kvp.Key),479 kvp => // Assembly level trait480 {481 Assert.Equal("Assembly", kvp.Key);482 var traitValue = Assert.Single(kvp.Value);483 Assert.Equal("Trait", traitValue);484 },485 kvp => // Class level trait486 {487 Assert.Equal("Class", kvp.Key);488 var traitValue = Assert.Single(kvp.Value);489 Assert.Equal("ClassWithTraitsOnTheoryDataRows", traitValue);490 },491 kvp => // Row level trait492 {493 Assert.Equal("Number", kvp.Key);494 var traitValue = Assert.Single(kvp.Value);495 Assert.Equal("42", traitValue);496 },497 kvp => // Theory level trait498 {499 Assert.Equal("Theory", kvp.Key);500 var traitValue = Assert.Single(kvp.Value);501 Assert.Equal("TestWithTraits", traitValue);502 }503 );504 }505 );506 }507 class ClassWithDisplayNameOnTheoryDataRows508 {509 public static IEnumerable<ITheoryDataRow> Data =>510 new[]511 {512 new TheoryDataRow(42) { TestDisplayName = "I am a special test" },513 new TheoryDataRow(2112),514 new TheoryDataRow(2600) { Skip = "I am skipped", TestDisplayName = "I am a skipped test" }515 };516 [Theory]517 [MemberData(nameof(Data))]518 public void TestWithDisplayName(int x)519 {520 Assert.Equal(96, x);521 }522 }523 [Fact]524 public async void CanSetDisplayNameFromTheoryDataRow_Preenumerated()525 {526 var discoverer = new TheoryDiscoverer();527 var testMethod = Mocks.TestMethod<ClassWithDisplayNameOnTheoryDataRows>(nameof(ClassWithDisplayNameOnTheoryDataRows.TestWithDisplayName));528 var factAttribute = testMethod.Method.GetCustomAttributes(typeof(FactAttribute)).Single();529 var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);530 Assert.Collection(531 testCases.OrderBy(tc => tc.TestCaseDisplayName),532 testCase =>533 {534 Assert.IsType<XunitSkippedDataRowTestCase>(testCase);535 Assert.Equal("I am a skipped test(x: 2600)", testCase.TestCaseDisplayName);536 },537 testCase =>538 {539 Assert.IsType<XunitPreEnumeratedTheoryTestCase>(testCase);540 Assert.Equal("I am a special test(x: 42)", testCase.TestCaseDisplayName);541 },...

Full Screen

Full Screen

XunitTestFrameworkDiscovererTests.cs

Source:XunitTestFrameworkDiscovererTests.cs Github

copy

Full Screen

...21 {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)...

Full Screen

Full Screen

TestMethodRunnerTests.cs

Source:TestMethodRunnerTests.cs Github

copy

Full Screen

...6using NSubstitute;7using Xunit;8using Xunit.Sdk;9using Xunit.v3;10public class TestMethodRunnerTests11{12 [Fact]13 public static async void Messages()14 {15 var summary = new RunSummary { Total = 4, Failed = 2, Skipped = 1, Time = 21.12m };16 var messageBus = new SpyMessageBus();17 var testCase = Mocks.TestCase<ClassUnderTest>("Passing");18 var runner = TestableTestMethodRunner.Create(messageBus, new[] { testCase }, result: summary);19 var result = await runner.RunAsync();20 Assert.Equal(result.Total, summary.Total);21 Assert.Equal(result.Failed, summary.Failed);22 Assert.Equal(result.Skipped, summary.Skipped);23 Assert.Equal(result.Time, summary.Time);24 Assert.False(runner.TokenSource.IsCancellationRequested);25 Assert.Collection(26 messageBus.Messages,27 msg =>28 {29 var starting = Assert.IsAssignableFrom<_TestMethodStarting>(msg);30 Assert.Equal("Passing", starting.TestMethod);31 },32 msg =>33 {34 var finished = Assert.IsAssignableFrom<_TestMethodFinished>(msg);35 Assert.Equal(21.12m, finished.ExecutionTime);36 Assert.Equal(2, finished.TestsFailed);37 Assert.Equal(4, finished.TestsRun);38 Assert.Equal(1, finished.TestsSkipped);39 }40 );41 }42 [Fact]43 public static async void FailureInQueueOfTestMethodStarting_DoesNotQueueTestMethodFinished_DoesNotRunTestCases()44 {45 var messages = new List<_MessageSinkMessage>();46 var messageBus = Substitute.For<IMessageBus>();47 messageBus48 .QueueMessage(null!)49 .ReturnsForAnyArgs(callInfo =>50 {51 var msg = callInfo.Arg<_MessageSinkMessage>();52 messages.Add(msg);53 if (msg is _TestMethodStarting)54 throw new InvalidOperationException();55 return true;56 });57 var runner = TestableTestMethodRunner.Create(messageBus);58 var ex = await Record.ExceptionAsync(() => runner.RunAsync());59 Assert.IsType<InvalidOperationException>(ex);60 var starting = Assert.Single(messages);61 Assert.IsAssignableFrom<_TestMethodStarting>(starting);62 Assert.Empty(runner.TestCasesRun);63 }64 [Fact]65 public static async void RunTestCaseAsync_AggregatorIncludesPassedInExceptions()66 {67 var messageBus = new SpyMessageBus();68 var ex = new DivideByZeroException();69 var runner = TestableTestMethodRunner.Create(messageBus, aggregatorSeedException: ex);70 await runner.RunAsync();71 Assert.Same(ex, runner.RunTestCaseAsync_AggregatorResult);72 Assert.Empty(messageBus.Messages.OfType<_TestMethodCleanupFailure>());73 }74 [Fact]75 public static async void FailureInAfterTestMethodStarting_GivesErroredAggregatorToTestCaseRunner_NoCleanupFailureMessage()76 {77 var messageBus = new SpyMessageBus();78 var runner = TestableTestMethodRunner.Create(messageBus);79 var ex = new DivideByZeroException();80 runner.AfterTestMethodStarting_Callback = aggregator => aggregator.Add(ex);81 await runner.RunAsync();82 Assert.Same(ex, runner.RunTestCaseAsync_AggregatorResult);83 Assert.Empty(messageBus.Messages.OfType<_TestMethodCleanupFailure>());84 }85 [Fact]86 public static async void FailureInBeforeTestMethodFinished_ReportsCleanupFailure_DoesNotIncludeExceptionsFromAfterTestMethodStarting()87 {88 var messageBus = new SpyMessageBus();89 var testCases = new[] { Mocks.TestCase<TestAssemblyRunnerTests.RunAsync>("Messages") };90 var runner = TestableTestMethodRunner.Create(messageBus, testCases);91 var startingException = new DivideByZeroException();92 var finishedException = new InvalidOperationException();93 runner.AfterTestMethodStarting_Callback = aggregator => aggregator.Add(startingException);94 runner.BeforeTestMethodFinished_Callback = aggregator => aggregator.Add(finishedException);95 await runner.RunAsync();96 var cleanupFailure = Assert.Single(messageBus.Messages.OfType<_TestMethodCleanupFailure>());97 Assert.Equal(typeof(InvalidOperationException).FullName, cleanupFailure.ExceptionTypes.Single());98 }99 [Fact]100 public static async void Cancellation_TestMethodStarting_DoesNotCallExtensibilityMethods()101 {102 var messageBus = new SpyMessageBus(msg => !(msg is _TestMethodStarting));103 var runner = TestableTestMethodRunner.Create(messageBus);104 await runner.RunAsync();105 Assert.True(runner.TokenSource.IsCancellationRequested);106 Assert.False(runner.AfterTestMethodStarting_Called);107 Assert.False(runner.BeforeTestMethodFinished_Called);108 }109 [Fact]110 public static async void Cancellation_TestMethodFinished_CallsExtensibilityMethods()111 {112 var messageBus = new SpyMessageBus(msg => !(msg is _TestMethodFinished));113 var runner = TestableTestMethodRunner.Create(messageBus);114 await runner.RunAsync();115 Assert.True(runner.TokenSource.IsCancellationRequested);116 Assert.True(runner.AfterTestMethodStarting_Called);117 Assert.True(runner.BeforeTestMethodFinished_Called);118 }119 [Fact]120 public static async void Cancellation_TestMethodCleanupFailure_SetsCancellationToken()121 {122 var messageBus = new SpyMessageBus(msg => !(msg is _TestMethodCleanupFailure));123 var runner = TestableTestMethodRunner.Create(messageBus);124 runner.BeforeTestMethodFinished_Callback = aggregator => aggregator.Add(new Exception());125 await runner.RunAsync();126 Assert.True(runner.TokenSource.IsCancellationRequested);127 }128 [Fact]129 public static async void SignalingCancellationStopsRunningMethods()130 {131 var passing = Mocks.TestCase<ClassUnderTest>("Passing");132 var other = Mocks.TestCase<ClassUnderTest>("Other");133 var runner = TestableTestMethodRunner.Create(testCases: new[] { passing, other }, cancelInRunTestCaseAsync: true);134 await runner.RunAsync();135 var testCase = Assert.Single(runner.TestCasesRun);136 Assert.Same(passing, testCase);137 }138 [Fact]139 public static async void TestContextInspection()140 {141 var runner = TestableTestMethodRunner.Create();142 await runner.RunAsync();143 Assert.NotNull(runner.AfterTestMethodStarting_Context);144 Assert.Equal(TestEngineStatus.Running, runner.AfterTestMethodStarting_Context.TestAssemblyStatus);145 Assert.Equal(TestEngineStatus.Running, runner.AfterTestMethodStarting_Context.TestCollectionStatus);146 Assert.Equal(TestEngineStatus.Running, runner.AfterTestMethodStarting_Context.TestClassStatus);147 Assert.Equal(TestEngineStatus.Initializing, runner.AfterTestMethodStarting_Context.TestMethodStatus);148 Assert.Equal(TestPipelineStage.TestMethodExecution, runner.AfterTestMethodStarting_Context.PipelineStage);149 Assert.Null(runner.AfterTestMethodStarting_Context.TestCaseStatus);150 Assert.Null(runner.AfterTestMethodStarting_Context.TestStatus);151 Assert.Same(runner.TestMethod, runner.AfterTestMethodStarting_Context.TestMethod);152 Assert.NotNull(runner.RunTestCaseAsync_Context);153 Assert.Equal(TestEngineStatus.Running, runner.RunTestCaseAsync_Context.TestAssemblyStatus);154 Assert.Equal(TestEngineStatus.Running, runner.RunTestCaseAsync_Context.TestCollectionStatus);155 Assert.Equal(TestEngineStatus.Running, runner.RunTestCaseAsync_Context.TestClassStatus);156 Assert.Equal(TestEngineStatus.Running, runner.RunTestCaseAsync_Context.TestMethodStatus);157 Assert.Null(runner.RunTestCaseAsync_Context.TestCaseStatus);158 Assert.Null(runner.RunTestCaseAsync_Context.TestStatus);159 Assert.Same(runner.TestMethod, runner.RunTestCaseAsync_Context.TestMethod);160 Assert.NotNull(runner.BeforeTestMethodFinished_Context);161 Assert.Equal(TestEngineStatus.Running, runner.BeforeTestMethodFinished_Context.TestAssemblyStatus);162 Assert.Equal(TestEngineStatus.Running, runner.BeforeTestMethodFinished_Context.TestCollectionStatus);163 Assert.Equal(TestEngineStatus.Running, runner.BeforeTestMethodFinished_Context.TestClassStatus);164 Assert.Equal(TestEngineStatus.CleaningUp, runner.BeforeTestMethodFinished_Context.TestMethodStatus);165 Assert.Null(runner.BeforeTestMethodFinished_Context.TestCaseStatus);166 Assert.Null(runner.BeforeTestMethodFinished_Context.TestStatus);167 Assert.Same(runner.TestMethod, runner.BeforeTestMethodFinished_Context.TestMethod);168 }169 class ClassUnderTest170 {171 [Fact]172 public void Passing() { }173 [Fact]174 public void Other() { }175 }176 class TestableTestMethodRunner : TestMethodRunner<TestMethodRunnerContext<_ITestCase>, _ITestCase>177 {178 readonly bool cancelInRunTestCaseAsync;179 readonly _IReflectionTypeInfo @class;180 readonly IMessageBus messageBus;181 readonly _IReflectionMethodInfo method;182 readonly RunSummary result;183 readonly IReadOnlyCollection<_ITestCase> testCases;184 readonly _ITestClass testClass;185 public readonly ExceptionAggregator Aggregator;186 public bool AfterTestMethodStarting_Called;187 public TestContext? AfterTestMethodStarting_Context;188 public Action<ExceptionAggregator> AfterTestMethodStarting_Callback = _ => { };189 public bool BeforeTestMethodFinished_Called;190 public TestContext? BeforeTestMethodFinished_Context;191 public Action<ExceptionAggregator> BeforeTestMethodFinished_Callback = _ => { };192 public Exception? RunTestCaseAsync_AggregatorResult;193 public TestContext? RunTestCaseAsync_Context;194 public readonly _ITestMethod TestMethod;195 public readonly CancellationTokenSource TokenSource;196 public List<_ITestCase> TestCasesRun = new();197 TestableTestMethodRunner(198 _ITestClass testClass,199 _ITestMethod testMethod,200 _IReflectionTypeInfo @class,201 _IReflectionMethodInfo method,202 IReadOnlyCollection<_ITestCase> testCases,203 IMessageBus messageBus,204 ExceptionAggregator aggregator,205 CancellationTokenSource cancellationTokenSource,206 RunSummary result,207 bool cancelInRunTestCaseAsync)208 {209 this.testClass = testClass;210 TestMethod = testMethod;211 this.@class = @class;212 this.method = method;213 this.testCases = testCases;214 this.messageBus = messageBus;215 Aggregator = aggregator;216 TokenSource = cancellationTokenSource;217 this.result = result;218 this.cancelInRunTestCaseAsync = cancelInRunTestCaseAsync;219 }220 public static TestableTestMethodRunner Create(221 IMessageBus? messageBus = null,222 _ITestCase[]? testCases = null,223 RunSummary? result = null,224 Exception? aggregatorSeedException = null,225 bool cancelInRunTestCaseAsync = false)226 {227 if (testCases == null)228 testCases = new[] { Mocks.TestCase<ClassUnderTest>("Passing") };229 var firstTestCase = testCases.First();230 var aggregator = new ExceptionAggregator();231 if (aggregatorSeedException != null)232 aggregator.Add(aggregatorSeedException);233 return new TestableTestMethodRunner(234 firstTestCase.TestClass ?? throw new InvalidOperationException("testCase.TestClass must not be null"),235 firstTestCase.TestMethod ?? throw new InvalidOperationException("testCase.TestMethod must not be null"),236 firstTestCase.TestClass.Class as _IReflectionTypeInfo ?? throw new InvalidOperationException("testCase.TestClass.Class must be based on reflection"),237 firstTestCase.TestMethod.Method as _IReflectionMethodInfo ?? throw new InvalidOperationException("testCase.TestMethod.Method must be based on reflection"),238 testCases,239 messageBus ?? new SpyMessageBus(),240 aggregator,241 new CancellationTokenSource(),242 result ?? new RunSummary(),243 cancelInRunTestCaseAsync244 );245 }246 protected override ValueTask AfterTestMethodStarting(TestMethodRunnerContext<_ITestCase> ctxt)247 {248 AfterTestMethodStarting_Called = true;249 AfterTestMethodStarting_Context = TestContext.Current;250 AfterTestMethodStarting_Callback(Aggregator);251 return default;252 }253 protected override ValueTask BeforeTestMethodFinished(TestMethodRunnerContext<_ITestCase> ctxt)254 {255 BeforeTestMethodFinished_Called = true;256 BeforeTestMethodFinished_Context = TestContext.Current;257 BeforeTestMethodFinished_Callback(Aggregator);258 return default;259 }260 public ValueTask<RunSummary> RunAsync() =>261 RunAsync(new(testClass, TestMethod, @class, method, testCases, messageBus, Aggregator, TokenSource));262 protected override ValueTask<RunSummary> RunTestCaseAsync(263 TestMethodRunnerContext<_ITestCase> ctxt,264 _ITestCase testCase)265 {266 if (cancelInRunTestCaseAsync)267 TokenSource.Cancel();268 RunTestCaseAsync_AggregatorResult = Aggregator.ToException();269 RunTestCaseAsync_Context = TestContext.Current;270 TestCasesRun.Add(testCase);271 return new(result);272 }273 }274}...

Full Screen

Full Screen

TestMethodTestCaseTests.cs

Source:TestMethodTestCaseTests.cs Github

copy

Full Screen

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

Full Screen

Full Screen

XunitTestCaseTests.cs

Source:XunitTestCaseTests.cs Github

copy

Full Screen

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

Mocks.TestCases.cs

Source:Mocks.TestCases.cs Github

copy

Full Screen

...60 IReadOnlyDictionary<string, IReadOnlyList<string>>? traits = null,61 string? fileName = null,62 int? lineNumber = null,63 string? uniqueID = null) =>64 TestCase(TestMethod<TClassUnderTest>(methodName), displayName, skipReason, traits, fileName, lineNumber, uniqueID);65 public static _ITestCase TestCase(66 string typeName,67 string methodName,68 string? displayName = null,69 string? skipReason = null,70 IReadOnlyDictionary<string, IReadOnlyList<string>>? traits = null,71 string? fileName = null,72 int? lineNumber = null,73 string? uniqueID = null) =>74 TestCase(TestMethod(typeName, methodName), displayName, skipReason, traits, fileName, lineNumber, uniqueID);75 public static _ITestCase TestCase(76 _ITestMethod? testMethod = null,77 string? displayName = null,78 string? skipReason = null,79 IReadOnlyDictionary<string, IReadOnlyList<string>>? traits = null,80 string? fileName = null,81 int? lineNumber = null,82 string? uniqueID = null)83 {84 testMethod ??= TestMethod();85 displayName ??= $"{testMethod.TestClass.Class.Name}.{testMethod.Method.Name}";86 traits ??= GetTraits(testMethod.Method);87 uniqueID ??= "case-id";88 var testCollection = testMethod.TestClass.TestCollection;89 var testClass = testMethod.TestClass;90 var result = Substitute.For<_ITestCase, InterfaceProxy<_ITestCase>>();91 result.TestCaseDisplayName.Returns(displayName);92 result.SkipReason.Returns(skipReason);93 result.SourceFilePath.Returns(fileName);94 result.SourceLineNumber.Returns(lineNumber);95 result.TestCollection.Returns(testCollection);96 result.TestClass.Returns(testClass);97 result.TestMethod.Returns(testMethod);98 result.Traits.Returns(traits);99 result.UniqueID.Returns(uniqueID);100 return result;101 }102 public static _ITestClass TestClass<TClassUnderTest>(103 _ITestCollection? collection = null,104 string? uniqueID = null) =>105 TestClass(106 TypeInfo<TClassUnderTest>(),107 collection,108 uniqueID109 );110 public static _ITestClass TestClass(111 string? typeName,112 _IMethodInfo[]? methods = null,113 _IReflectionAttributeInfo[]? attributes = null,114 _ITypeInfo? baseType = null,115 _ITestCollection? collection = null,116 string? uniqueID = null) =>117 TestClass(TypeInfo(typeName, methods, attributes, baseType), collection, uniqueID);118 public static _ITestClass TestClass(119 _ITypeInfo? typeInfo = null,120 _ITestCollection? collection = null,121 string? uniqueID = null)122 {123 typeInfo ??= TypeInfo();124 collection ??= TestCollection();125 uniqueID ??= "class-id";126 var result = Substitute.For<_ITestClass, InterfaceProxy<_ITestClass>>();127 result.Class.Returns(typeInfo);128 result.TestCollection.Returns(collection);129 result.UniqueID.Returns(uniqueID);130 return result;131 }132 public static _ITestCollection TestCollection(133 Assembly assembly,134 _ITypeInfo? definition = null,135 string? displayName = null,136 string? uniqueID = null) =>137 TestCollection(TestAssembly(assembly), definition, displayName, uniqueID);138 public static _ITestCollection TestCollection(139 _ITestAssembly? assembly = null,140 _ITypeInfo? definition = null,141 string? displayName = null,142 string? uniqueID = null)143 {144 assembly ??= TestAssembly();145 displayName ??= "Mock test collection";146 uniqueID ??= "collection-id";147 var result = Substitute.For<_ITestCollection, InterfaceProxy<_ITestCollection>>();148 result.CollectionDefinition.Returns(definition);149 result.DisplayName.Returns(displayName);150 result.TestAssembly.Returns(assembly);151 result.UniqueID.Returns(uniqueID);152 return result;153 }154 public static _ITestMethod TestMethod(155 string? typeName = null,156 string? methodName = null,157 string? displayName = null,158 string? skip = null,159 int timeout = 0,160 _IParameterInfo[]? parameters = null,161 _IReflectionAttributeInfo[]? classAttributes = null,162 _IReflectionAttributeInfo[]? methodAttributes = null,163 _ITestCollection? collection = null,164 string? uniqueID = null)165 {166 parameters ??= EmptyParameterInfos;167 classAttributes ??= EmptyAttributeInfos;168 methodAttributes ??= EmptyAttributeInfos;169 // Ensure that there's a FactAttribute, or else it's not technically a test method170 var factAttribute = methodAttributes.FirstOrDefault(attr => typeof(FactAttribute).IsAssignableFrom(attr.Attribute.GetType()));171 if (factAttribute == null)172 {173 factAttribute = FactAttribute(displayName, skip, timeout);174 methodAttributes = methodAttributes.Concat(new[] { factAttribute }).ToArray();175 }176 var testClass = TestClass(typeName, attributes: classAttributes, collection: collection);177 var methodInfo = MethodInfo(methodName, methodAttributes, parameters, testClass.Class);178 return TestMethod(methodInfo, testClass, uniqueID);179 }180 public static _ITestMethod TestMethod<TClassUnderTest>(181 string methodName,182 _ITestCollection? collection = null,183 string? uniqueID = null) =>184 TestMethod(MethodInfo<TClassUnderTest>(methodName), TestClass<TClassUnderTest>(collection), uniqueID);185 public static _ITestMethod TestMethod(186 _IMethodInfo methodInfo,187 _ITestClass testClass,188 string? uniqueID = null)189 {190 uniqueID ??= "method-id";191 var result = Substitute.For<_ITestMethod, InterfaceProxy<_ITestMethod>>();192 result.Method.Returns(methodInfo);193 result.TestClass.Returns(testClass);194 result.UniqueID.Returns(uniqueID);195 return result;196 }197 }198}...

Full Screen

Full Screen

FactDiscovererTests.cs

Source:FactDiscovererTests.cs Github

copy

Full Screen

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

Full Screen

Full Screen

ExecutionErrorTestCaseRunnerTests.cs

Source:ExecutionErrorTestCaseRunnerTests.cs Github

copy

Full Screen

...64 public static ExecutionErrorTestCase ExecutionErrorTestCase(65 string message,66 _IMessageSink? diagnosticMessageSink = null)67 {68 var testMethod = Mocks.TestMethod();69 return new(70 TestMethodDisplay.ClassAndMethod,71 TestMethodDisplayOptions.None,72 testMethod,73 message74 );75 }76}...

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3;3{4 {5 public void TestMethod()6 {7 var mock = new Xunit.v3.Mocks();8 var test = mock.TestMethod("TestNamespace.TestClass.TestMethod");9 Assert.NotNull(test);10 }11 }12}

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit.v3;2using Xunit.v3.Mocks;3{4 {5 public void TestMethod()6 {7 var mockTestAssembly = Mocks.TestAssembly("MockTestAssembly");8 var mockTestClass = Mocks.TestClass("MockTestClass");9 var mockTestMethod = Mocks.TestMethod("MockTestMethod");10 var mockTest = Mocks.Test("MockTest", mockTestAssembly, mockTestClass, mockTestMethod);11 var mockTestCollection = Mocks.TestCollection("MockTestCollection");12 var mockTestCollectionRunner = Mocks.TestCollectionRunner(mockTestCollection, new[] { mockTest });13 var mockMessageBus = Mocks.MessageBus();14 var mockTestAssemblyRunner = Mocks.TestAssemblyRunner(mockTestAssembly, new[] { mockTestCollectionRunner });15 var mockTestRunner = Mocks.TestRunner(mockTest, mockMessageBus, mockTestAssemblyRunner);16 var mockTestCase = Mocks.TestCase("MockTestCase", mockTestAssembly, mockTestClass, mockTestMethod);17 var mockTestOutputHelper = Mocks.TestOutputHelper();18 mockTestRunner.RunAsync();19 mockTestRunner.RunAsync(mockTestCase);20 mockTestRunner.RunAsync(mockTestCase, mockMessageBus);21 mockTestRunner.RunAsync(mockTestCase, mockMessageBus, mockTestOutputHelper);22 }23 }24}

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2{3 {4 public void TestMethod1()5 {6 TestMethod();7 }8 }9}

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit.v3;2using Xunit.v3.Mocks;3{4 {5 public void TestMethod()6 {7 Mocks.TestMethod();8 }9 }10}

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3.Mocks;3{4 {5 public void TestMethod()6 {7 var mock = new Xunit.v3.Mocks();8 mock.TestMethod();9 }10 }11}

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit.v3.Mocks;2{3 {4 public void TestMethod()5 {6 TestMethod();7 }8 }9}10System.InvalidOperationException: No test method found for 'Test.TestClass.TestMethod()'. at Xunit.Sdk.TestMethodRunner`1..ctor(IMessageSink diagnosticMessageSink, IMessageBus messageBus, ITestMethod testMethod, Object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.TestMethodRunner`1..ctor(IMessageSink diagnosticMessageSink, IMessageBus messageBus, ITestMethod testMethod, Object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.TestMethodRunner`1..ctor(IMessageSink diagnosticMessageSink, IMessageBus messageBus, ITestMethod testMethod, Object[] constructorArguments, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(IXunitTestCase testCase, String displayName, String skipReason, Object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(IXunitTestCase testCase, String displayName, String skipReason, Object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(IXunitTestCase testCase, String displayName, String skipReason, Object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(IXunitTestCase testCase, String displayName, String skipReason, Object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(IXunitTestCase testCase, String displayName, String skipReason, Object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(IXunitTestCase testCase, String displayName, String skipReason, Object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) at Xunit.Sdk.XunitTestRunner..ctor(

Full Screen

Full Screen

TestMethod

Using AI Code Generation

copy

Full Screen

1using Xunit;2using Xunit.v3.Mocks;3{4 {5 public void TestMethod()6 {7 }8 }9}10using Xunit;11using Xunit.v3.Mocks;12{13 {14 public void TestMethod()15 {16 }17 }18}19using Xunit;20using Xunit.v3.Mocks;21{22 {23 public void TestMethod()24 {25 }26 }27}28using Xunit;29using Xunit.v3.Mocks;30{31 {32 public void TestMethod()33 {34 }35 }36}37using Xunit;38using Xunit.v3.Mocks;39{40 {41 public void TestMethod()42 {43 }44 }45}46using Xunit;47using Xunit.v3.Mocks;

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