diff --git a/src/DependencyModules.Testing/Impl/TestParameterResolver.cs b/src/DependencyModules.Testing/Impl/TestParameterResolver.cs index afe69fc..ce6f6b2 100644 --- a/src/DependencyModules.Testing/Impl/TestParameterResolver.cs +++ b/src/DependencyModules.Testing/Impl/TestParameterResolver.cs @@ -23,6 +23,10 @@ namespace DependencyModules.Testing.Impl; public sealed class TestParameterResolver { private readonly ITestMethodContext _testMethod; + + // ParameterInfo compares by reference, and two threads that call GetParameters on the same + // method for the first time can each get a different array. Both phases use this one array. + private readonly ParameterInfo[] _parameters; private readonly Dictionary> _valueProviders = new(); private bool _setupRan; @@ -34,6 +38,7 @@ public sealed class TestParameterResolver public TestParameterResolver(ITestMethodContext testMethod) { _testMethod = testMethod; + _parameters = testMethod.Method.GetParameters(); } /// @@ -47,7 +52,7 @@ public TestParameterResolver(ITestMethodContext testMethod) /// The collection backing the test's container. public void SetupServiceCollection(IServiceCollection serviceCollection) { - foreach (var parameterInfo in _testMethod.Method.GetParameters()) + foreach (var parameterInfo in _parameters) { var providers = parameterInfo .GetCustomAttributes() @@ -98,7 +103,7 @@ public void SetupServiceCollection(IServiceCollection serviceCollection) ); } - var parameterList = _testMethod.Method.GetParameters(); + var parameterList = _parameters; var arguments = new List(data); for (var i = data.Length; i < parameterList.Length; i++) diff --git a/tests/DependencyModules.Tests/TestingTests/SharedRegistrationsTests.cs b/tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs similarity index 81% rename from tests/DependencyModules.Tests/TestingTests/SharedRegistrationsTests.cs rename to tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs index 318410b..146fc71 100644 --- a/tests/DependencyModules.Tests/TestingTests/SharedRegistrationsTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs @@ -3,9 +3,8 @@ using DependencyModules.Testing.Attributes.Interfaces; using DependencyModules.Testing.Impl; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.TestingTests; +namespace DependencyModules.Specs.TestingTests; /// /// Which services a test pins, decided without a container or a test framework in the way. @@ -14,7 +13,7 @@ namespace DependencyModules.Tests.TestingTests; /// One test per row of the rule, because the rule has been wrong once already and the way it was /// wrong was a case nobody had written down. /// -public class SharedRegistrationsTests +public partial class SharedRegistrationsTests { private interface IThing; @@ -75,36 +74,36 @@ private static void None() { } /// The row the first version of this rule got wrong, and the one a scaffolded project hits /// first: a plain application service the handler writes to and the test reads. /// - [Fact] + [VerifyTest] public void AnUnmarkedParameterIsPinned() { - Assert.Equal([typeof(IThing)], Collect(nameof(Plain))); + Verify(Collect(nameof(Plain)).SequenceEqual([typeof(IThing)])); } - [Fact] + [VerifyTest] public void EveryParameterIsPinned() { - Assert.Equal([typeof(IThing), typeof(IOther)], Collect(nameof(Bare))); + Verify(Collect(nameof(Bare)).SequenceEqual([typeof(IThing), typeof(IOther)])); } /// A mock needs no attribute to be pinned, which is what makes the rule general. - [Fact] + [VerifyTest] public void AMockIsPinnedLikeAnythingElse() { - Assert.Equal([typeof(IThing)], Collect(nameof(Mocked))); + Verify(Collect(nameof(Mocked)).SequenceEqual([typeof(IThing)])); } /// Redundant now, and still allowed: it is how a driving parameter asks for reuse. - [Fact] + [VerifyTest] public void SharedOnAValueParameterChangesNothing() { - Assert.Equal(Collect(nameof(Plain)), Collect(nameof(Marked))); + Verify(Collect(nameof(Marked)).SequenceEqual(Collect(nameof(Plain)))); } - [Fact] + [VerifyTest] public void ATestWithNoParametersPinsNothing() { - Assert.Empty(Collect(nameof(None))); + Verify(Collect(nameof(None)).Count == 0); } // ---------------------------------------------------------------- the exceptions @@ -112,35 +111,35 @@ public void ATestWithNoParametersPinsNothing() /// /// The parameter that drives the application is not pinned, because it builds the containers. /// - [Fact] + [VerifyTest] public void AParameterTheHarnessDrivesWithIsNotPinned() { var pinned = Collect(nameof(Driving), new DrivenByAttribute()); - Assert.Equal([typeof(IThing)], pinned); + Verify(pinned.SequenceEqual([typeof(IThing)])); } /// /// And it stays unpinned even asked to be. Pinning a driver is not a preference that could go /// either way; it turns the isolation off while the test believes it is on. /// - [Fact] + [VerifyTest] public void IsolatedWinsOverAnExplicitShared() { - Assert.Empty(Collect(nameof(DrivingAndMarked), new DrivenByAttribute())); + Verify(Collect(nameof(DrivingAndMarked), new DrivenByAttribute()).Count == 0); } - [Fact] + [VerifyTest] public void AnAttributeDecliningUnpinsItsParameter() { - Assert.Empty(Collect(nameof(Declined))); + Verify(Collect(nameof(Declined)).Count == 0); } /// The container itself is the one question pinning cannot answer. - [Fact] + [VerifyTest] public void TheServiceProviderIsNeverPinned() { - Assert.Equal([typeof(IThing)], Collect(nameof(Container))); + Verify(Collect(nameof(Container)).SequenceEqual([typeof(IThing)])); } // ---------------------------------------------------------------- what no parameter holds @@ -148,7 +147,7 @@ public void TheServiceProviderIsNeverPinned() /// /// A harness keeps its own per-test services by naming them, since no parameter holds them. /// - [Fact] + [VerifyTest] public void AnAttributeCanPinWhatNoParameterHolds() { var shared = new TestExportAttribute(typeof(IOther)) @@ -157,27 +156,27 @@ public void AnAttributeCanPinWhatNoParameterHolds() Shared = true, }; - Assert.Equal([typeof(IThing), typeof(IOther)], Collect(nameof(Plain), shared)); + Verify(Collect(nameof(Plain), shared).SequenceEqual([typeof(IThing), typeof(IOther)])); } /// An export nothing holds stays per container until it asks. - [Fact] + [VerifyTest] public void AnExportIsNotPinnedUnlessItAsks() { var isolated = new TestExportAttribute(typeof(IOther)) { Implementation = typeof(Thing) }; - Assert.Equal([typeof(IThing)], Collect(nameof(Plain), isolated)); + Verify(Collect(nameof(Plain), isolated).SequenceEqual([typeof(IThing)])); } /// /// The parameter is the narrower statement and wins, which is how every other precedence in the /// harness resolves. Isolating it would recreate the bug the rule exists to fix. /// - [Fact] + [VerifyTest] public void AnExportTheTestHoldsIsPinnedEvenWhenItDeclined() { var isolated = new TestExportAttribute(typeof(IThing)) { Implementation = typeof(Thing) }; - Assert.Equal([typeof(IThing)], Collect(nameof(Plain), isolated)); + Verify(Collect(nameof(Plain), isolated).SequenceEqual([typeof(IThing)])); } } diff --git a/tests/DependencyModules.Tests/TestingTests/TestContainerSourceUnitTests.cs b/tests/DependencyModules.Specs/TestingTests/TestContainerSourceUnitTests.cs similarity index 79% rename from tests/DependencyModules.Tests/TestingTests/TestContainerSourceUnitTests.cs rename to tests/DependencyModules.Specs/TestingTests/TestContainerSourceUnitTests.cs index e9af8a4..501abae 100644 --- a/tests/DependencyModules.Tests/TestingTests/TestContainerSourceUnitTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/TestContainerSourceUnitTests.cs @@ -1,14 +1,13 @@ using DependencyModules.Testing.Attributes.Interfaces; using DependencyModules.Testing.Impl; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.TestingTests; +namespace DependencyModules.Specs.TestingTests; /// /// The source driven directly, for the parts a test running through a framework cannot observe. /// -public class TestContainerSourceUnitTests +public partial class TestContainerSourceUnitTests { private interface IThing; @@ -65,7 +64,7 @@ public Harness(Action compose, Type[] pinned, Type[] named) /// Every container goes to the runner, which is what makes destroying them the runner's business /// rather than the caller's. /// - [Fact] + [VerifyTest] public async Task EveryContainerBuiltIsHandedToTheRunner() { var harness = new Harness(services => services.AddSingleton()); @@ -73,13 +72,13 @@ public async Task EveryContainerBuiltIsHandedToTheRunner() var first = await harness.Source.CreateAsync(); var second = await harness.Source.CreateAsync(); - Assert.Equal([first, second], harness.Tracked); + Verify(harness.Tracked.SequenceEqual([first, second])); } /// /// Startup runs against each one. A container that skipped it is not the one the test composed. /// - [Fact] + [VerifyTest] public async Task StartupRunsForEveryContainer() { var harness = new Harness(services => services.AddSingleton()); @@ -87,14 +86,14 @@ public async Task StartupRunsForEveryContainer() var first = await harness.Source.CreateAsync(); var second = await harness.Source.CreateAsync(); - Assert.Equal([first, second], harness.Started); + Verify(harness.Started.SequenceEqual([first, second])); } /// /// A pinned service survives its container being disposed, which is the whole reason the template /// uses an instance registration rather than a factory returning the same object. /// - [Fact] + [VerifyTest] public async Task APinnedDisposableIsNotDisposedByTheContainersItIsHandedTo() { var tracked = new Tracked(); @@ -104,20 +103,20 @@ public async Task APinnedDisposableIsNotDisposedByTheContainersItIsHandedTo() var first = await harness.Source.CreateAsync(); var second = await harness.Source.CreateAsync(); - Assert.Same(tracked, first.GetRequiredService()); - Assert.Same(tracked, second.GetRequiredService()); + Verify(ReferenceEquals(tracked, first.GetRequiredService())); + Verify(ReferenceEquals(tracked, second.GetRequiredService())); ((IDisposable)first).Dispose(); ((IDisposable)second).Dispose(); - Assert.Equal(0, tracked.Disposals); + Verify(tracked.Disposals == 0); } /// /// A type registered more than once keeps every registration, because collapsing the set to its /// last member would leave anything injecting the sequence one element long. /// - [Fact] + [VerifyTest] public async Task PinningKeepsEveryRegistrationOfAService() { var harness = new Harness( @@ -131,15 +130,15 @@ public async Task PinningKeepsEveryRegistrationOfAService() var built = await harness.Source.CreateAsync(); - Assert.Equal(2, built.GetServices().Count()); - Assert.Equal(harness.Pin.GetServices(), built.GetServices()); + Verify(built.GetServices().Count() == 2); + Verify(built.GetServices().SequenceEqual(harness.Pin.GetServices())); } /// /// Pinning takes the instances from IEnumerable<T>, which holds no keyed /// registration. The keyed registrations of a pinned service stay as they were written. /// - [Fact] + [VerifyTest] public async Task PinningKeepsTheKeyedRegistrationsOfAService() { var harness = new Harness( @@ -154,16 +153,21 @@ public async Task PinningKeepsTheKeyedRegistrationsOfAService() var built = await harness.Source.CreateAsync(); - Assert.Same(harness.Pin.GetRequiredService(), built.GetRequiredService()); - Assert.NotNull(built.GetRequiredKeyedService("before")); - Assert.NotNull(built.GetRequiredKeyedService("after")); + Verify( + ReferenceEquals( + harness.Pin.GetRequiredService(), + built.GetRequiredService() + ) + ); + Verify(built.GetRequiredKeyedService("before") is not null); + Verify(built.GetRequiredKeyedService("after") is not null); } /// /// A service an attribute names is one the test asked to share. When the test's container cannot /// produce it, every container built after it would get its own instance with no message. /// - [Fact] + [VerifyTest] public async Task ANamedServiceThatCannotBeBuiltIsReported() { var harness = new Harness( @@ -175,41 +179,41 @@ public async Task ANamedServiceThatCannotBeBuiltIsReported() named: [typeof(IThing)] ); - var refused = await Assert.ThrowsAsync(async () => + var refused = await ThrowsExactlyAsync(async () => await harness.Source.CreateAsync() ); - Assert.Contains(typeof(IThing).FullName!, refused.Message); - Assert.Contains("cannot build it", refused.Message); - Assert.Equal("cannot build it", refused.InnerException?.Message); + Verify(refused.Message.Contains(typeof(IThing).FullName!)); + Verify(refused.Message.Contains("cannot build it")); + Verify(refused.InnerException?.Message == "cannot build it"); } /// /// Nothing is built until something asks, so a test that never rebuilds pays for none of this. /// - [Fact] + [VerifyTest] public void NothingIsBuiltUntilAsked() { var harness = new Harness(services => services.AddSingleton()); - Assert.Empty(harness.Tracked); - Assert.Empty(harness.Started); + Verify(harness.Tracked.Count == 0); + Verify(harness.Started.Count == 0); } /// /// A source nobody initialized says so, rather than answering with a container built from /// nothing. /// - [Fact] + [VerifyTest] public async Task AnUninitializedSourceRefuses() { var source = new TestContainerSource(); - var refused = await Assert.ThrowsAsync(async () => + var refused = await ThrowsExactlyAsync(async () => await source.CreateAsync() ); - Assert.Contains("never initialized", refused.Message); + Verify(refused.Message.Contains("never initialized")); } /// @@ -222,7 +226,7 @@ await source.CreateAsync() /// eagerly here turned that message into a failure at container build for every test that took /// such a parameter and never resolved it. /// - [Fact] + [VerifyTest] public async Task APinnedServiceThatCannotBeBuiltIsLeftAlone() { var harness = new Harness( @@ -239,20 +243,20 @@ public async Task APinnedServiceThatCannotBeBuiltIsLeftAlone() var built = await harness.Source.CreateAsync(); - Assert.NotNull(built.GetRequiredService()); + Verify(built.GetRequiredService() is not null); - var refused = Assert.Throws(() => + var refused = ThrowsExactly(() => built.GetRequiredService() ); - Assert.Equal("name the fix", refused.Message); + Verify(refused.Message == "name the fix"); } /// /// A pinned type nothing registered is inert, which is what lets the set be drawn from a /// signature without filtering it first. /// - [Fact] + [VerifyTest] public async Task APinnedTypeNothingRegisteredIsInert() { var harness = new Harness( @@ -264,7 +268,7 @@ public async Task APinnedTypeNothingRegisteredIsInert() var built = await harness.Source.CreateAsync(); - Assert.NotNull(built.GetRequiredService()); - Assert.Null(built.GetService()); + Verify(built.GetRequiredService() is not null); + Verify(built.GetService() is null); } } diff --git a/tests/DependencyModules.Tests/TestingTests/TestExportAttributeTests.cs b/tests/DependencyModules.Specs/TestingTests/TestExportAttributeTests.cs similarity index 62% rename from tests/DependencyModules.Tests/TestingTests/TestExportAttributeTests.cs rename to tests/DependencyModules.Specs/TestingTests/TestExportAttributeTests.cs index dc76e00..4b43153 100644 --- a/tests/DependencyModules.Tests/TestingTests/TestExportAttributeTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/TestExportAttributeTests.cs @@ -1,15 +1,14 @@ using DependencyModules.Testing.Attributes; using DependencyModules.Testing.Attributes.Interfaces; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.TestingTests; +namespace DependencyModules.Specs.TestingTests; /// /// [TestExport] lets a test override a registration for the duration of that test, so the lifetime /// and implementation it produces have to match what was asked for. /// -public class TestExportAttributeTests +public partial class TestExportAttributeTests { private interface IThing; @@ -17,28 +16,28 @@ private class Thing : IThing; private class OtherThing : IThing; - [Fact] + [VerifyTest] public void DefaultsToTransient() { - Assert.Equal(ServiceLifetime.Transient, new TestExportAttribute(typeof(IThing)).Lifetime); + Verify(new TestExportAttribute(typeof(IThing)).Lifetime == ServiceLifetime.Transient); } - [Fact] + [VerifyTest] public void DefaultsToNoSeparateImplementation() { - Assert.Null(new TestExportAttribute(typeof(IThing)).Implementation); + Verify(new TestExportAttribute(typeof(IThing)).Implementation is null); } - [Fact] + [VerifyTest] public void ExposesTheServiceItWasGiven() { - Assert.Equal(typeof(IThing), new TestExportAttribute(typeof(IThing)).Service); + Verify(new TestExportAttribute(typeof(IThing)).Service == typeof(IThing)); } - [Theory] - [InlineData(ServiceLifetime.Singleton)] - [InlineData(ServiceLifetime.Scoped)] - [InlineData(ServiceLifetime.Transient)] + [VerifyTest] + [Row(ServiceLifetime.Singleton)] + [Row(ServiceLifetime.Scoped)] + [Row(ServiceLifetime.Transient)] public void RegistersWithTheRequestedLifetime(ServiceLifetime lifetime) { var attribute = new TestExportAttribute(typeof(IThing)) @@ -49,23 +48,23 @@ public void RegistersWithTheRequestedLifetime(ServiceLifetime lifetime) var collection = Setup(attribute); - var descriptor = Assert.Single(collection); - Assert.Equal(lifetime, descriptor.Lifetime); - Assert.Equal(typeof(IThing), descriptor.ServiceType); - Assert.Equal(typeof(Thing), descriptor.ImplementationType); + var descriptor = Single(collection); + Verify(descriptor.Lifetime == lifetime); + Verify(descriptor.ServiceType == typeof(IThing)); + Verify(descriptor.ImplementationType == typeof(Thing)); } - [Fact] + [VerifyTest] public void WithoutAnImplementation_RegistersTheServiceAsItsOwnImplementation() { var collection = Setup(new TestExportAttribute(typeof(Thing))); - var descriptor = Assert.Single(collection); - Assert.Equal(typeof(Thing), descriptor.ServiceType); - Assert.Equal(typeof(Thing), descriptor.ImplementationType); + var descriptor = Single(collection); + Verify(descriptor.ServiceType == typeof(Thing)); + Verify(descriptor.ImplementationType == typeof(Thing)); } - [Fact] + [VerifyTest] public void RegisteredServiceResolvesFromTheProvider() { var collection = Setup( @@ -78,7 +77,7 @@ public void RegisteredServiceResolvesFromTheProvider() var provider = collection.BuildServiceProvider(); - Assert.IsType(provider.GetService()); + Verify(provider.GetService()?.GetType() == typeof(OtherThing)); } /// @@ -86,16 +85,16 @@ public void RegisteredServiceResolvesFromTheProvider() /// It used to carry a no-op StartupAsync purely because the two lived on one interface; pinning /// the split here means re-adding a lifecycle hook has to be a decision rather than an accident. /// - [Fact] + [VerifyTest] public void RegistersServicesWithoutTakingPartInTestStartup() { - Assert.IsAssignableFrom( - new TestExportAttribute(typeof(IThing)) - ); - Assert.False(new TestExportAttribute(typeof(IThing)) is ITestStartupAttribute); + object attribute = new TestExportAttribute(typeof(IThing)); + + Verify(attribute is ITestServiceSetupAttribute); + Verify(attribute is not ITestStartupAttribute); } - [Fact] + [VerifyTest] public void AppliesToAssembliesClassesAndMethods() { var usage = typeof(TestExportAttribute) @@ -103,10 +102,10 @@ public void AppliesToAssembliesClassesAndMethods() .Cast() .Single(); - Assert.True(usage.ValidOn.HasFlag(AttributeTargets.Assembly)); - Assert.True(usage.ValidOn.HasFlag(AttributeTargets.Class)); - Assert.True(usage.ValidOn.HasFlag(AttributeTargets.Method)); - Assert.True(usage.AllowMultiple); + Verify(usage.ValidOn.HasFlag(AttributeTargets.Assembly)); + Verify(usage.ValidOn.HasFlag(AttributeTargets.Class)); + Verify(usage.ValidOn.HasFlag(AttributeTargets.Method)); + Verify(usage.AllowMultiple); } /// diff --git a/tests/DependencyModules.Tests/TestingTests/TestOutputLoggerProviderTests.cs b/tests/DependencyModules.Specs/TestingTests/TestOutputLoggerProviderTests.cs similarity index 73% rename from tests/DependencyModules.Tests/TestingTests/TestOutputLoggerProviderTests.cs rename to tests/DependencyModules.Specs/TestingTests/TestOutputLoggerProviderTests.cs index 8993429..979ff9c 100644 --- a/tests/DependencyModules.Tests/TestingTests/TestOutputLoggerProviderTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/TestOutputLoggerProviderTests.cs @@ -2,9 +2,8 @@ using DependencyModules.Testing.Attributes.Interfaces; using DependencyModules.Testing.Impl; using Microsoft.Extensions.Logging; -using Xunit; -namespace DependencyModules.Tests.TestingTests; +namespace DependencyModules.Specs.TestingTests; /// /// What the logger writes, read from a provider of the test's own rather than from a framework's @@ -12,11 +11,11 @@ namespace DependencyModules.Tests.TestingTests; /// /// /// Through the constructor that takes a provider, because CurrentTest.Provider is one static -/// for the whole assembly, and this assembly runs its test classes in parallel. The path through +/// for the whole assembly, and this assembly runs its tests in parallel. The path through /// CurrentTest is asserted under each framework, in SutProject.Tests and /// SutProject.NUnitTests. /// -public class TestOutputLoggerProviderTests +public partial class TestOutputLoggerProviderTests { private sealed class RecordingTest(bool running = true) : ICurrentTestProvider { @@ -41,7 +40,7 @@ public bool TryWriteLine(string message) } } - [Fact] + [VerifyTest] public void AnEntryIsOneLineInTheConsoleLoggersSingleLineFormat() { var test = new RecordingTest(); @@ -50,26 +49,26 @@ public void AnEntryIsOneLineInTheConsoleLoggersSingleLineFormat() .CreateLogger("Shop.OrderService") .LogInformation(new EventId(7), "Order {Id} accepted", 42); - Assert.Equal(["info: Shop.OrderService[7] Order 42 accepted"], test.Lines); + Verify(test.Lines.SequenceEqual(["info: Shop.OrderService[7] Order 42 accepted"])); } - [Theory] - [InlineData(LogLevel.Trace, "trce")] - [InlineData(LogLevel.Debug, "dbug")] - [InlineData(LogLevel.Information, "info")] - [InlineData(LogLevel.Warning, "warn")] - [InlineData(LogLevel.Error, "fail")] - [InlineData(LogLevel.Critical, "crit")] + [VerifyTest] + [Row(LogLevel.Trace, "trce")] + [Row(LogLevel.Debug, "dbug")] + [Row(LogLevel.Information, "info")] + [Row(LogLevel.Warning, "warn")] + [Row(LogLevel.Error, "fail")] + [Row(LogLevel.Critical, "crit")] public void EachLevelHasTheConsoleLoggersName(LogLevel level, string name) { var test = new RecordingTest(); new TestOutputLoggerProvider(test).CreateLogger("Category").Log(level, "message"); - Assert.Equal([$"{name}: Category[0] message"], test.Lines); + Verify(test.Lines.SequenceEqual([$"{name}: Category[0] message"])); } - [Fact] + [VerifyTest] public void AnExceptionIsOnTheLinesAfterTheEntry() { var test = new RecordingTest(); @@ -77,10 +76,12 @@ public void AnExceptionIsOnTheLinesAfterTheEntry() new TestOutputLoggerProvider(test).CreateLogger("Category").LogError(exception, "failed"); - Assert.Equal(["fail: Category[0] failed" + Environment.NewLine + exception], test.Lines); + Verify( + test.Lines.SequenceEqual(["fail: Category[0] failed" + Environment.NewLine + exception]) + ); } - [Fact] + [VerifyTest] public void NoneIsNotEnabled() { var test = new RecordingTest(); @@ -88,35 +89,35 @@ public void NoneIsNotEnabled() logger.Log(LogLevel.None, "message"); - Assert.False(logger.IsEnabled(LogLevel.None)); - Assert.Empty(test.Lines); + Verify(!logger.IsEnabled(LogLevel.None)); + Verify(test.Lines.Count == 0); } - [Fact] + [VerifyTest] public void AnEntryWithNothingToShowIsDropped() { var test = new RecordingTest(); new TestOutputLoggerProvider(test).CreateLogger("Category").LogInformation(""); - Assert.Empty(test.Lines); + Verify(test.Lines.Count == 0); } /// /// The case a logger meets on a background thread after its test has finished. A logger that /// threw here would fail the application under test instead of the test. /// - [Fact] + [VerifyTest] public void AnEntryLoggedWhileNoTestIsRunningIsDropped() { var test = new RecordingTest(running: false); new TestOutputLoggerProvider(test).CreateLogger("Category").LogInformation("message"); - Assert.Empty(test.Lines); + Verify(test.Lines.Count == 0); } - [Fact] + [VerifyTest] public void AScopeChangesNothing() { var test = new RecordingTest(); @@ -127,6 +128,6 @@ public void AScopeChangesNothing() logger.LogInformation("message"); } - Assert.Equal(["info: Category[0] message"], test.Lines); + Verify(test.Lines.SequenceEqual(["info: Category[0] message"])); } } diff --git a/tests/DependencyModules.Tests/TestingTests/TestParameterResolverTests.cs b/tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs similarity index 88% rename from tests/DependencyModules.Tests/TestingTests/TestParameterResolverTests.cs rename to tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs index da59d94..868d08a 100644 --- a/tests/DependencyModules.Tests/TestingTests/TestParameterResolverTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs @@ -3,9 +3,8 @@ using DependencyModules.Testing.Attributes.Interfaces; using DependencyModules.Testing.Impl; using Microsoft.Extensions.DependencyInjection; -using Xunit; -namespace DependencyModules.Tests.TestingTests; +namespace DependencyModules.Specs.TestingTests; /// /// Drives TestParameterResolver directly, without a test framework around it. @@ -15,7 +14,7 @@ namespace DependencyModules.Tests.TestingTests; /// unrelated integration test failing, if at all. The resolver is the piece an NUnit integration /// would share, which makes its behaviour a contract rather than an implementation detail. /// -public class TestParameterResolverTests +public partial class TestParameterResolverTests { private interface IThing; @@ -36,7 +35,7 @@ private class NeedsAValue(IThing thing, string text) public string Text { get; } = text; } - [Fact] + [VerifyTest] public async Task ResolvesAServiceFromTheContainer() { var arguments = await Resolve( @@ -44,27 +43,27 @@ public async Task ResolvesAServiceFromTheContainer() services => services.AddSingleton() ); - Assert.IsType(Assert.Single(arguments)); + Verify(Single(arguments)?.GetType() == typeof(Thing)); } /// /// A test asking for the container itself cannot have it resolved from the container. /// - [Fact] + [VerifyTest] public async Task ServiceProviderParameterGetsTheContainerItself() { var (resolver, provider) = Build(nameof(Samples.WantsTheProvider), _ => { }); var arguments = await resolver.ResolveArgumentsAsync(provider, []); - Assert.Same(provider, Assert.Single(arguments)); + Verify(ReferenceEquals(provider, Single(arguments))); } /// /// A data row owns the parameters it covers, so its arguments are passed through untouched even /// when the container could have supplied that type. /// - [Fact] + [VerifyTest] public async Task DataTakesTheLeadingParametersAndTheContainerTakesTheRest() { var (resolver, provider) = Build( @@ -74,9 +73,9 @@ public async Task DataTakesTheLeadingParametersAndTheContainerTakesTheRest() var arguments = await resolver.ResolveArgumentsAsync(provider, [42]); - Assert.Equal(2, arguments.Length); - Assert.Equal(42, arguments[0]); - Assert.IsType(arguments[1]); + Verify(arguments.Length == 2); + Verify(Equals(arguments[0], 42)); + Verify(arguments[1]?.GetType() == typeof(Thing)); } /// @@ -84,7 +83,7 @@ public async Task DataTakesTheLeadingParametersAndTheContainerTakesTheRest() /// afterwards — the property that lets [Mock] replace a service for the whole test rather than /// only for the parameter holding it. /// - [Fact] + [VerifyTest] public async Task ParameterAttributeRegistrationBeatsTheModuleRegistration() { var arguments = await Resolve( @@ -92,14 +91,14 @@ public async Task ParameterAttributeRegistrationBeatsTheModuleRegistration() services => services.AddSingleton() ); - Assert.IsType(Assert.Single(arguments)); + Verify(Single(arguments)?.GetType() == typeof(Other)); } /// /// A provider that returns null stands aside rather than forcing a null argument, so several /// attributes can sit on one parameter with the first that answers winning. /// - [Fact] + [VerifyTest] public async Task AProviderReturningNullDefersToTheNextOne() { var arguments = await Resolve( @@ -107,10 +106,10 @@ public async Task AProviderReturningNullDefersToTheNextOne() services => services.AddSingleton() ); - Assert.IsType(Assert.Single(arguments)); + Verify(Single(arguments)?.GetType() == typeof(Other)); } - [Fact] + [VerifyTest] public async Task ResolvesKeyedServices() { var arguments = await Resolve( @@ -122,14 +121,14 @@ public async Task ResolvesKeyedServices() } ); - Assert.IsType(Assert.Single(arguments)); + Verify(Single(arguments)?.GetType() == typeof(Other)); } /// /// An unregistered concrete type is constructed from the container, so a test can name the class /// under test without registering it. /// - [Fact] + [VerifyTest] public async Task ConstructsAnUnregisteredConcreteType() { var arguments = await Resolve( @@ -137,27 +136,27 @@ public async Task ConstructsAnUnregisteredConcreteType() services => services.AddSingleton() ); - var value = Assert.IsType(Assert.Single(arguments)); + var value = Is(Single(arguments)); - Assert.IsType(value.Thing); - Assert.Equal("supplied", value.Text); + Verify(value.Thing.GetType() == typeof(Thing)); + Verify(value.Text == "supplied"); } /// /// Resolving without the setup phase would skip every parameter attribute silently, so a [Mock] /// parameter would hand back the real service. It fails loudly instead. /// - [Fact] + [VerifyTest] public async Task ResolvingBeforeSetupThrows() { var resolver = new TestParameterResolver(ContextFor(nameof(Samples.OneService))); var provider = new ServiceCollection().BuildServiceProvider(); - var exception = await Assert.ThrowsAsync(() => + var exception = await ThrowsExactlyAsync(() => resolver.ResolveArgumentsAsync(provider, []) ); - Assert.Contains(nameof(TestParameterResolver.SetupServiceCollection), exception.Message); + Verify(exception.Message.Contains(nameof(TestParameterResolver.SetupServiceCollection))); } /// @@ -166,7 +165,7 @@ public async Task ResolvingBeforeSetupThrows() /// the service under test kept the real implementation while the test held a double it believed /// was wired in. /// - [Fact] + [VerifyTest] public async Task KeyedMockReplacesTheKeyedRegistration() { var (resolver, provider) = Build( @@ -176,14 +175,14 @@ public async Task KeyedMockReplacesTheKeyedRegistration() var arguments = await resolver.ResolveArgumentsAsync(provider, []); - Assert.IsType(Assert.Single(arguments)); - Assert.IsType(provider.GetRequiredKeyedService("primary")); + Verify(Single(arguments)?.GetType() == typeof(Other)); + Verify(provider.GetRequiredKeyedService("primary").GetType() == typeof(Other)); } /// /// And it does not spill into the unkeyed slot, where nothing asked for it. /// - [Fact] + [VerifyTest] public void KeyedMockRegistersNothingUnkeyed() { var (_, provider) = Build( @@ -191,14 +190,14 @@ public void KeyedMockRegistersNothingUnkeyed() services => services.AddKeyedSingleton("primary") ); - Assert.Null(provider.GetService()); + Verify(provider.GetService() is null); } /// /// A key the mock did not name is left alone, so mocking one keyed implementation leaves its /// siblings real. /// - [Fact] + [VerifyTest] public void KeyedMockLeavesOtherKeysAlone() { var (_, provider) = Build( @@ -210,11 +209,11 @@ public void KeyedMockLeavesOtherKeysAlone() } ); - Assert.IsType(provider.GetRequiredKeyedService("secondary")); + Verify(provider.GetRequiredKeyedService("secondary").GetType() == typeof(Thing)); } /// Control: an unkeyed mock still replaces the unkeyed registration. - [Fact] + [VerifyTest] public async Task UnkeyedMockReplacesTheUnkeyedRegistration() { var arguments = await Resolve( @@ -222,7 +221,7 @@ public async Task UnkeyedMockReplacesTheUnkeyedRegistration() services => services.AddSingleton() ); - Assert.IsType(Assert.Single(arguments)); + Verify(Single(arguments)?.GetType() == typeof(Other)); } /// @@ -234,7 +233,7 @@ public async Task UnkeyedMockReplacesTheUnkeyedRegistration() /// half of it the resolver owns: whatever was registered before it, the double registered here /// is the one the container ends up with. /// - [Fact] + [VerifyTest] public async Task AMockOnAParameter_BeatsARegistrationMadeBeforeIt() { var services = new ServiceCollection(); @@ -249,14 +248,14 @@ public async Task AMockOnAParameter_BeatsARegistrationMadeBeforeIt() var arguments = await resolver.ResolveArgumentsAsync(services.BuildServiceProvider(), []); - Assert.IsType(Assert.Single(arguments)); + Verify(Single(arguments)?.GetType() == typeof(Other)); } /// /// And the service under test sees the same double, which is why [Mock] registers at all rather /// than merely supplying an argument. /// - [Fact] + [VerifyTest] public void AMockOnAParameter_IsWhatTheContainerHandsOut() { var services = new ServiceCollection(); @@ -265,10 +264,12 @@ public void AMockOnAParameter_IsWhatTheContainerHandsOut() services.AddSingleton(); resolver.SetupServiceCollection(services); - Assert.IsType(services.BuildServiceProvider().GetRequiredService()); + Verify( + services.BuildServiceProvider().GetRequiredService().GetType() == typeof(Other) + ); } - [Fact] + [VerifyTest] public void SetupIsOfferedEveryParameter() { var services = new ServiceCollection(); @@ -277,7 +278,7 @@ public void SetupIsOfferedEveryParameter() ContextFor(nameof(Samples.TwoRegisteringAttributes)) ).SetupServiceCollection(services); - Assert.Equal(2, services.Count); + Verify(services.Count == 2); } // ---- harness -------------------------------------------------------------------------------