diff --git a/CHANGELOG.md b/CHANGELOG.md index 0530ee0..42cceda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- A [VerificationGlue](https://ipjohnson.github.io/DependencyModules/guide/testing-verificationglue) + page in the testing guide. VerificationGlue.Tests 0.6.0-preview.1 gives `[VerifyTest]` tests the + services of a module from its attribute, and applies the attributes of + `DependencyModules.Testing` through `ModuleTestComposition`. No DependencyModules package + references VerificationGlue. +- `integ-tests/SutProject.VerificationGlueTests`, which runs SutProject's modules under + VerificationGlue.Tests in the build workflow. + ## [1.8.0] - 2026-11-28 This release adds collections and `Func` registrations to the generated code. It also adds diff --git a/DependencyModules.sln b/DependencyModules.sln index 6d62644..0f326d9 100644 --- a/DependencyModules.sln +++ b/DependencyModules.sln @@ -52,6 +52,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DependencyModules.CodeFixes EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DependencyModules.Specs", "tests\DependencyModules.Specs\DependencyModules.Specs.csproj", "{3B3E3C52-B0EB-46DF-98D9-212D60CB68D4}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SutProject.VerificationGlueTests", "integ-tests\SutProject.VerificationGlueTests\SutProject.VerificationGlueTests.csproj", "{8BCC5D74-F347-4059-B87D-3BA977324D6B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -314,6 +316,18 @@ Global {3B3E3C52-B0EB-46DF-98D9-212D60CB68D4}.Release|x64.Build.0 = Release|Any CPU {3B3E3C52-B0EB-46DF-98D9-212D60CB68D4}.Release|x86.ActiveCfg = Release|Any CPU {3B3E3C52-B0EB-46DF-98D9-212D60CB68D4}.Release|x86.Build.0 = Release|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Debug|x64.ActiveCfg = Debug|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Debug|x64.Build.0 = Debug|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Debug|x86.ActiveCfg = Debug|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Debug|x86.Build.0 = Debug|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Release|Any CPU.Build.0 = Release|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Release|x64.ActiveCfg = Release|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Release|x64.Build.0 = Release|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Release|x86.ActiveCfg = Release|Any CPU + {8BCC5D74-F347-4059-B87D-3BA977324D6B}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -341,5 +355,6 @@ Global {D1AEA1C9-CD76-4664-956B-706962E78E3D} = {FB161494-E422-4D4E-BA04-3473C2EB13B0} {1233A4FF-C8EE-4422-A26F-EF18D3FFA0F2} = {FB161494-E422-4D4E-BA04-3473C2EB13B0} {3B3E3C52-B0EB-46DF-98D9-212D60CB68D4} = {F4DC9AA2-7F61-4DEE-A7D1-2BCDBEEFD1C5} + {8BCC5D74-F347-4059-B87D-3BA977324D6B} = {DC7C95FE-F58F-4F16-8DFA-87E1B67DCEAE} EndGlobalSection EndGlobal diff --git a/Directory.Build.props b/Directory.Build.props index caed670..1e12b69 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -61,11 +61,11 @@ - 0.5.0-preview.1 + 0.6.0-preview.1 diff --git a/README.md b/README.md index 96f5352..34d956b 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ DependencyModules is a source generator for `Microsoft.Extensions.DependencyInjection`. You put attributes on your classes. When you compile the project, the generator writes the code that registers these classes in an `IServiceCollection`. The generated code does not use reflection to find services at run time. -A module is a partial class that registers the services of a project. A module can use other modules. The test packages build a service provider from your modules for each xUnit or NUnit test. +A module is a partial class that registers the services of a project. A module can use other modules. The test packages build a service provider from your modules for each xUnit or NUnit test. VerificationGlue.Tests builds one for each `[VerifyTest]` test from the module attributes. Documentation: [ipjohnson.github.io/DependencyModules](https://ipjohnson.github.io/DependencyModules/) @@ -90,6 +90,7 @@ The test gets its parameters from a new service provider. After the test, the te - [Decorators](https://ipjohnson.github.io/DependencyModules/guide/decorators) and [interception](https://ipjohnson.github.io/DependencyModules/guide/interception): code around services. - [Environments](https://ipjohnson.github.io/DependencyModules/guide/environments): registrations that occur only in some environments. - [Testing](https://ipjohnson.github.io/DependencyModules/guide/testing): xUnit and NUnit tests with modules, mocks, and more service providers in a test. +- [VerificationGlue](https://ipjohnson.github.io/DependencyModules/guide/testing-verificationglue): `[VerifyTest]` tests that get the services of a module from its attribute, with `DependencyModules.Testing` and no adapter package. - [Native AOT](https://ipjohnson.github.io/DependencyModules/guide/aot): generated factories and trimming. ## Sample projects @@ -99,6 +100,7 @@ The `integ-tests` folder contains projects that reference the source projects of - `SutProject` and `SecondarySutProject`: modules and services. - `SutProject.Tests`: xUnit tests of these modules. - `SutProject.NUnitTests`: NUnit tests of these modules. +- `SutProject.VerificationGlueTests`: VerificationGlue.Tests tests of these modules. - `ConsoleTestProject`: a console application. - `web/WebApiApp` and `web/WebApiApp.Tests`: an ASP.NET Core application and its tests. diff --git a/integ-tests/SutProject.VerificationGlueTests/CircularReferenceModules/CircularModuleTests.cs b/integ-tests/SutProject.VerificationGlueTests/CircularReferenceModules/CircularModuleTests.cs new file mode 100644 index 0000000..f94e301 --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/CircularReferenceModules/CircularModuleTests.cs @@ -0,0 +1,31 @@ +using SecondarySutProject.CircularReferenceModules; + +namespace SutProject.VerificationGlueTests.CircularReferenceModules; + +public partial class CircularModuleTests +{ + [VerifyTest] + [ModuleA] + public void LoadModuleATest(ServiceA serviceA, ServiceB serviceB) + { + Verify(serviceA is not null); + Verify(serviceB is not null); + } + + [VerifyTest] + [ModuleB] + public void LoadModuleBTest(ServiceA serviceA, ServiceB serviceB) + { + Verify(serviceA is not null); + Verify(serviceB is not null); + } + + [VerifyTest] + [ModuleA] + [ModuleB] + public void LoadModuleBothTest(ServiceA serviceA, ServiceB serviceB) + { + Verify(serviceA is not null); + Verify(serviceB is not null); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/EnvironmentTests/EnvironmentSeedingTests.cs b/integ-tests/SutProject.VerificationGlueTests/EnvironmentTests/EnvironmentSeedingTests.cs new file mode 100644 index 0000000..f1ef4ed --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/EnvironmentTests/EnvironmentSeedingTests.cs @@ -0,0 +1,66 @@ +using System.Reflection; +using DependencyModules.Runtime; +using DependencyModules.Runtime.Attributes; +using DependencyModules.Runtime.Interfaces; + +namespace SutProject.VerificationGlueTests.EnvironmentTests; + +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] +public class SeededEnvironmentAttribute(string name) : Attribute, IModuleEnvironmentProvider +{ + public IModuleEnvironment? ProvideEnvironment(MethodInfo testMethod) => + new ModuleEnvironment(false, name); +} + +public interface IGatedByEnvironment; + +[SingletonService(Realm = typeof(SeededEnvironmentModule))] +[IfEnvironment("seeded-environment")] +public class GatedByEnvironment : IGatedByEnvironment; + +[DependencyModule(OnlyRealm = true)] +public partial class SeededEnvironmentModule; + +[SeededEnvironmentModule] +public partial class EnvironmentSeedingTests +{ + [VerifyTest] + [SeededEnvironment("seeded-environment")] + public void AGatedRegistrationAppliesUnderTheSeededEnvironment( + IServiceProvider provider, + IModuleEnvironment environment + ) + { + Verify(provider.GetService(typeof(IGatedByEnvironment)) is GatedByEnvironment); + Verify(environment.EnvironmentName == "seeded-environment"); + } + + [VerifyTest] + [SeededEnvironment("other-environment")] + public void TheSameRegistrationIsAbsentUnderAnotherEnvironment(IServiceProvider provider) + { + Verify(provider.GetService(typeof(IGatedByEnvironment)) is null); + } +} + +[SeededEnvironmentModule] +[SeededEnvironment("seeded-environment")] +public partial class EnvironmentSeedingPrecedenceTests +{ + [VerifyTest] + public void AClassLevelSeedApplies(IServiceProvider provider) + { + Verify(provider.GetService(typeof(IGatedByEnvironment)) is GatedByEnvironment); + } + + [VerifyTest] + [SeededEnvironment("inner-environment")] + public void TheMethodsSeedBeatsTheClasses( + IServiceProvider provider, + IModuleEnvironment environment + ) + { + Verify(provider.GetService(typeof(IGatedByEnvironment)) is null); + Verify(environment.EnvironmentName == "inner-environment"); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/KeyedTests/KeyedMockTests.cs b/integ-tests/SutProject.VerificationGlueTests/KeyedTests/KeyedMockTests.cs new file mode 100644 index 0000000..62ef1b5 --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/KeyedTests/KeyedMockTests.cs @@ -0,0 +1,63 @@ +using DependencyModules.Runtime.Attributes; +using Microsoft.Extensions.DependencyInjection; +using VerificationGlue.Mocks; + +namespace SutProject.VerificationGlueTests.KeyedTests; + +public interface IKeyedRegistration +{ + string Key { get; } +} + +[SingletonService(Key = "A", Realm = typeof(KeyedModule))] +public class AKeyedRegistration : IKeyedRegistration +{ + public string Key => "A"; +} + +[SingletonService(Key = "C", Realm = typeof(KeyedModule))] +public class CKeyedRegistration : IKeyedRegistration +{ + public string Key => "C"; +} + +[SingletonService(Realm = typeof(KeyedModule))] +public class CKeyedDependency([FromKeyedServices("C")] IKeyedRegistration registration) +{ + public IKeyedRegistration Registration { get; } = registration; +} + +[DependencyModule(OnlyRealm = true)] +public partial class KeyedModule; + +[KeyedModule] +public partial class KeyedMockTests +{ + [VerifyTest] + public void AKeyedMockReachesTheServiceThatInjectsTheKey( + [Mock] [FromKeyedServices("C")] IKeyedRegistration registration, + CKeyedDependency dependency + ) + { + registration.Key.Returns("mocked"); + + Verify(ReferenceEquals(dependency.Registration, registration)); + Verify(dependency.Registration.Key == "mocked"); + } + + [VerifyTest] + public void AKeyedMockLeavesTheOtherKeys( + [Mock] [FromKeyedServices("C")] IKeyedRegistration registration, + [FromKeyedServices("A")] IKeyedRegistration aRegistration + ) + { + Verify(aRegistration is AKeyedRegistration); + Verify(registration is not CKeyedRegistration); + } + + [VerifyTest] + public void WithoutTheMockTheKeyedServiceIsReal(CKeyedDependency dependency) + { + Verify(dependency.Registration is CKeyedRegistration); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/Mocks/MockAliasTests.cs b/integ-tests/SutProject.VerificationGlueTests/Mocks/MockAliasTests.cs new file mode 100644 index 0000000..b765e7a --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/Mocks/MockAliasTests.cs @@ -0,0 +1,37 @@ +using DependencyModules.Testing.Attributes; +using VerificationGlue.Mocks; + +namespace SutProject.VerificationGlueTests.Mocks; + +// Both imported namespaces declare MockAttribute. [Mock] compiles because VerificationGlue.Tests +// adds a global MockAttribute alias to VerificationGlue.Mocks.MockAttribute. +[SutModule] +public partial class MockAliasTests +{ + [VerifyTest] + public void MockBindsThroughTheAlias( + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + } + + [VerifyTest] + public void DependencyModulesMockIsReadTheSameWay( + IDependencyOne dependencyOne, + [DependencyModules.Testing.Attributes.Mock] ISingletonService singletonService + ) + { + singletonService.GetName().Returns("from DependencyModules' Mock"); + + Verify(dependencyOne.SingletonService.GetName() == "from DependencyModules' Mock"); + } + + [VerifyTest] + [TestExport(typeof(IScopedService), Implementation = typeof(ScopedService))] + public void TheOtherTestingAttributesStillResolve(IDependencyOne dependencyOne) + { + Verify(dependencyOne.ScopedService is ScopedService); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/Mocks/MockTests.cs b/integ-tests/SutProject.VerificationGlueTests/Mocks/MockTests.cs new file mode 100644 index 0000000..64b8e0f --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/Mocks/MockTests.cs @@ -0,0 +1,35 @@ +using VerificationGlue.Mocks; + +namespace SutProject.VerificationGlueTests.Mocks; + +[SutModule] +public partial class MockTests +{ + [VerifyTest] + public void TheServiceReceivesTheMock( + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + Verify(scopedService is not ScopedService); + } + + [VerifyTest] + public void AMockSetUpWithReturnsAnswersTheService( + [Mock] ISingletonService singletonService, + IDependencyOne dependencyOne + ) + { + singletonService.GetName().Returns("mocked"); + + Verify(dependencyOne.SingletonService.GetName() == "mocked"); + } + + [VerifyTest] + public void ATestWithoutTheMockGetsTheRealService(IDependencyOne dependencyOne) + { + Verify(dependencyOne.ScopedService is ScopedService); + Verify(dependencyOne.SingletonService is SingletonService); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/ParameterizedModuleTests/ParameterizedModuleTests.cs b/integ-tests/SutProject.VerificationGlueTests/ParameterizedModuleTests/ParameterizedModuleTests.cs new file mode 100644 index 0000000..feaa1cd --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/ParameterizedModuleTests/ParameterizedModuleTests.cs @@ -0,0 +1,27 @@ +using SecondarySutProject.ParameterizedModules; + +namespace SutProject.VerificationGlueTests.ParameterizedModuleTests; + +public partial class ParameterizedModuleTests +{ + [VerifyTest] + [ParameterizedModule("local-string", 20, C = "CValue")] + public void ConstructorArgumentsAndNamedPropertiesReachTheModule( + SomeRuntimeDependency someRuntimeDependency + ) + { + Verify(someRuntimeDependency.SomeDependency == "local-string"); + Verify(someRuntimeDependency.IntDependency == 20); + Verify(someRuntimeDependency.CValue == "CValue"); + } + + [VerifyTest] + [SecondaryParameterizedModule] + public void AModuleThatComposesAParameterizedModulePassesItsArguments( + SomeRuntimeDependency someRuntimeDependency + ) + { + Verify(someRuntimeDependency.SomeDependency == "test-string"); + Verify(someRuntimeDependency.IntDependency == 10); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/RealmTests/RealmIsolationTests.cs b/integ-tests/SutProject.VerificationGlueTests/RealmTests/RealmIsolationTests.cs new file mode 100644 index 0000000..06e99ff --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/RealmTests/RealmIsolationTests.cs @@ -0,0 +1,45 @@ +using DependencyModules.Runtime.Attributes; +using SecondarySutProject; + +namespace SutProject.VerificationGlueTests.RealmTests; + +[DependencyModule(OnlyRealm = true)] +public partial class FirstRealmModule; + +[TransientService( + As = typeof(IDependencyOne), + Realm = typeof(FirstRealmModule), + Using = RegistrationType.Add +)] +public class RealmDependencyOne(ISingletonService singletonService, IScopedService scopedService) + : IDependencyOne +{ + public ISingletonService SingletonService { get; } = singletonService; + + public IScopedService ScopedService { get; } = scopedService; +} + +public partial class RealmIsolationTests +{ + // SutProject.Tests writes these in the other order. DependencyModules.xUnit moves the + // attributes declared in the test assembly after the others on one target, and VerificationGlue + // keeps the source order, so only this order loads FirstRealmModule last under both. + [VerifyTest] + [SecondarySutModule] + [FirstRealmModule] + public void OverrideDependencyWithRealm(IDependencyOne dependencyOne) + { + Verify(dependencyOne is RealmDependencyOne); + } + + [VerifyTest] + [TestRealmModule] + public void AnOnlyRealmModuleRegistersItsRealmOnly( + ITestRealmService realmService, + IServiceProvider serviceProvider + ) + { + Verify(realmService is TestRealmService); + Verify(serviceProvider.GetService(typeof(IDependencyOne)) is null); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/StandardTests/ContainerOfModuleTests.cs b/integ-tests/SutProject.VerificationGlueTests/StandardTests/ContainerOfModuleTests.cs new file mode 100644 index 0000000..a41563d --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/StandardTests/ContainerOfModuleTests.cs @@ -0,0 +1,24 @@ +using SecondarySutProject.ParameterizedModules; + +namespace SutProject.VerificationGlueTests.StandardTests; + +[Container] +public partial class ContainerOfModuleTests +{ + [VerifyTest] + public void TheNamedModuleRegistersItsServices(IDependencyOne dependencyOne) + { + Verify(dependencyOne is DependencyOne); + } + + [VerifyTest] + [ParameterizedModule("method-string", 5, C = "method-c")] + public void TheModuleAttributesInScopeLoadWithIt( + IDependencyOne dependencyOne, + SomeRuntimeDependency dependency + ) + { + Verify(dependencyOne is DependencyOne); + Verify(dependency.SomeDependency == "method-string"); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/StandardTests/LocalModuleTests.cs b/integ-tests/SutProject.VerificationGlueTests/StandardTests/LocalModuleTests.cs new file mode 100644 index 0000000..68946da --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/StandardTests/LocalModuleTests.cs @@ -0,0 +1,27 @@ +using DependencyModules.Runtime.Attributes; + +namespace SutProject.VerificationGlueTests.StandardTests; + +public interface IGreeter +{ + string Greet(string name); +} + +[SingletonService(Realm = typeof(LocalModule))] +public class Greeter : IGreeter +{ + public string Greet(string name) => $"Hello {name}"; +} + +[DependencyModule(OnlyRealm = true)] +public partial class LocalModule; + +[LocalModule] +public partial class LocalModuleTests +{ + [VerifyTest] + public void AModuleOfTheTestProjectRegistersItsServices(IGreeter greeter) + { + Verify(greeter.Greet("World") == "Hello World"); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/StandardTests/ModuleDuplicationTests.cs b/integ-tests/SutProject.VerificationGlueTests/StandardTests/ModuleDuplicationTests.cs new file mode 100644 index 0000000..548dc46 --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/StandardTests/ModuleDuplicationTests.cs @@ -0,0 +1,46 @@ +using DependencyModules.Runtime.Attributes; +using SecondarySutProject; + +namespace SutProject.VerificationGlueTests.StandardTests; + +[DependencyModule] +[SutModule] +public partial class TestModule; + +[DependencyModule] +[SutModule] +public partial class TestModule2; + +[DependencyModule] +[TestModule] +[TestModule2] +public partial class CombinedModule; + +[SutModule] +public partial class ModuleDuplicationTests +{ + [VerifyTest] + [SutModule] + public void AModuleOnTheClassAndTheMethodRegistersOnce(IEnumerable dependencies) + { + Verify(dependencies.Count() == 1); + } + + [VerifyTest] + [CombinedModule] + public void TwoModulesThatComposeOneModuleRegisterItOnce( + IEnumerable dependencies + ) + { + Verify(dependencies.Count() == 1); + } + + [VerifyTest] + [SecondarySutModule] + public void AModuleNamedDirectlyAndThroughAnotherRegistersOnce( + IEnumerable singletons + ) + { + Verify(singletons.Count() == 1); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/StandardTests/SimpleResolveTests.cs b/integ-tests/SutProject.VerificationGlueTests/StandardTests/SimpleResolveTests.cs new file mode 100644 index 0000000..8807c7c --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/StandardTests/SimpleResolveTests.cs @@ -0,0 +1,35 @@ +using SecondarySutProject; + +namespace SutProject.VerificationGlueTests.StandardTests; + +[SutModule] +public partial class SimpleResolveTests +{ + [VerifyTest] + public void SimpleTest(IDependencyOne dependencyOne) + { + Verify(dependencyOne is DependencyOne); + Verify(dependencyOne.SingletonService is SingletonService); + Verify(dependencyOne.ScopedService is ScopedService); + } + + [VerifyTest] + public void ResolveServiceProvider( + IDependencyOne dependencyOne, + IServiceProvider serviceProvider + ) + { + Verify(serviceProvider.GetService(typeof(IDependencyOne)) is DependencyOne); + Verify(dependencyOne is DependencyOne); + } +} + +public partial class SecondarySutProjectTests +{ + [VerifyTest] + [SecondarySutModule] + public void OverrideDependency(IDependencyOne dependencyOne) + { + Verify(dependencyOne is BetterDependencyOne); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/SutProject.VerificationGlueTests.csproj b/integ-tests/SutProject.VerificationGlueTests/SutProject.VerificationGlueTests.csproj new file mode 100644 index 0000000..c4181a8 --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/SutProject.VerificationGlueTests.csproj @@ -0,0 +1,36 @@ + + + + + net10.0 + enable + enable + False + + true + + + + + + + + + + + + + + + + + + + + diff --git a/integ-tests/SutProject.VerificationGlueTests/TestFramework/CurrentTestTests.cs b/integ-tests/SutProject.VerificationGlueTests/TestFramework/CurrentTestTests.cs new file mode 100644 index 0000000..7fe801e --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/TestFramework/CurrentTestTests.cs @@ -0,0 +1,72 @@ +using DependencyModules.Testing.Attributes.Interfaces; +using DependencyModules.Testing.Impl; +using Microsoft.Extensions.DependencyInjection; + +namespace SutProject.VerificationGlueTests.TestFramework; + +[SutModule] +public partial class CurrentTestTests +{ + [VerifyTest] + public void KeyIsTheTestContextOfTheRunningTest(TestContext context) + { + Verify(ReferenceEquals(CurrentTest.Key, context)); + } + + [VerifyTest] + public void DisplayNameIsTheDisplayNameOfTheTest(TestContext context) + { + Verify(CurrentTest.DisplayName == context.DisplayName); + } + + [VerifyTest] + public void AssemblyIsTheAssemblyOfTheTestClass() + { + Verify(CurrentTest.Assembly == typeof(CurrentTestTests).Assembly); + } + + [VerifyTest] + public void ALineIsWrittenToTheOutputOfTheTest() + { + Verify(CurrentTest.TryWriteLine("written through CurrentTest")); + } + + [VerifyTest] + [RecordCurrentTestAtStartup] + public void AStartupAttributeSeesTheRunningTest(StartupRecord record, TestContext context) + { + Verify(ReferenceEquals(record.Key, context)); + Verify(record.DisplayName == context.DisplayName); + } +} + +public sealed class StartupRecord +{ + public object? Key { get; set; } + + public string? DisplayName { get; set; } +} + +// Under DependencyModules.xUnit the container is built before the test runs, so this attribute +// sees no test there. VerificationGlue builds the container inside the test. +[AttributeUsage(AttributeTargets.Method)] +public sealed class RecordCurrentTestAtStartupAttribute + : Attribute, + ITestServiceSetupAttribute, + ITestStartupAttribute +{ + public void SetupServiceCollection( + ITestMethodContext testMethod, + IServiceCollection serviceCollection + ) => serviceCollection.AddSingleton(); + + public Task StartupAsync(ITestMethodContext testMethod, IServiceProvider serviceProvider) + { + var record = serviceProvider.GetRequiredService(); + + record.Key = CurrentTest.Key; + record.DisplayName = CurrentTest.DisplayName; + + return Task.CompletedTask; + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/TestFramework/InjectValueTests.cs b/integ-tests/SutProject.VerificationGlueTests/TestFramework/InjectValueTests.cs new file mode 100644 index 0000000..695be5c --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/TestFramework/InjectValueTests.cs @@ -0,0 +1,16 @@ +using DependencyModules.Testing.Attributes; + +namespace SutProject.VerificationGlueTests.TestFramework; + +public record InjectModel(IDependencyOne DependencyOne, string StringValue); + +[SutModule] +public partial class InjectValueTests +{ + [VerifyTest] + public void InjectTestValue([InjectValues("Hello World!")] InjectModel injectModel) + { + Verify(injectModel.DependencyOne is DependencyOne); + Verify(injectModel.StringValue == "Hello World!"); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/TestFramework/SharedTests.cs b/integ-tests/SutProject.VerificationGlueTests/TestFramework/SharedTests.cs new file mode 100644 index 0000000..95e7fca --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/TestFramework/SharedTests.cs @@ -0,0 +1,63 @@ +using System.Collections.Concurrent; +using DependencyModules.Testing.Attributes; +using VerificationGlue.Mocks; + +namespace SutProject.VerificationGlueTests.TestFramework; + +[Container(Scope = ContainerScope.Class)] +public partial class SharedTests +{ + private static readonly ConcurrentBag SharedInstances = []; + + private static readonly ConcurrentBag Mocks = []; + + private static readonly ConcurrentBag OwnInstances = []; + + [VerifyTest] + public void FirstTest( + [Shared] ISingletonService shared, + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + SharedInstances.Add(shared); + Mocks.Add(scopedService); + + Verify(SharedInstances.All(seen => ReferenceEquals(seen, shared))); + Verify(Mocks.Count(seen => ReferenceEquals(seen, scopedService)) == 1); + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + } + + [VerifyTest] + public void SecondTest( + [Shared] ISingletonService shared, + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + SharedInstances.Add(shared); + Mocks.Add(scopedService); + + Verify(SharedInstances.All(seen => ReferenceEquals(seen, shared))); + Verify(Mocks.Count(seen => ReferenceEquals(seen, scopedService)) == 1); + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + } + + [VerifyTest] + public void ATestWithoutSharedGetsItsOwnInstance(ISingletonService own) + { + OwnInstances.Add(own); + + Verify(!SharedInstances.Any(seen => ReferenceEquals(seen, own))); + Verify(OwnInstances.Count(seen => ReferenceEquals(seen, own)) == 1); + } + + [VerifyTest] + public void AnotherTestWithoutSharedGetsItsOwnInstance(ISingletonService own) + { + OwnInstances.Add(own); + + Verify(!SharedInstances.Any(seen => ReferenceEquals(seen, own))); + Verify(OwnInstances.Count(seen => ReferenceEquals(seen, own)) == 1); + } +} diff --git a/integ-tests/SutProject.VerificationGlueTests/TestFramework/TestExportTests.cs b/integ-tests/SutProject.VerificationGlueTests/TestFramework/TestExportTests.cs new file mode 100644 index 0000000..13318e1 --- /dev/null +++ b/integ-tests/SutProject.VerificationGlueTests/TestFramework/TestExportTests.cs @@ -0,0 +1,66 @@ +using DependencyModules.Testing.Attributes; +using Microsoft.Extensions.DependencyInjection; +using VerificationGlue.Mocks; + +namespace SutProject.VerificationGlueTests.TestFramework; + +public class ExportedSingletonService : ISingletonService +{ + public string GetName() => nameof(ExportedSingletonService); +} + +[SutModule] +public partial class TestExportTests +{ + [VerifyTest] + [TestExport(typeof(ISingletonService), Implementation = typeof(ExportedSingletonService))] + public void OverridesARegistrationForOneTest(ISingletonService singletonService) + { + Verify(singletonService is ExportedSingletonService); + } + + [VerifyTest] + public void TheOverrideDoesNotLeakIntoTheNextTest(ISingletonService singletonService) + { + Verify(singletonService is SingletonService); + } + + [VerifyTest] + [TestExport( + typeof(ISingletonService), + Implementation = typeof(ExportedSingletonService), + Lifetime = ServiceLifetime.Singleton + )] + public void HonoursTheLifetimeItIsGiven( + ISingletonService first, + IServiceProvider serviceProvider + ) + { + Verify(ReferenceEquals(serviceProvider.GetRequiredService(), first)); + } +} + +// DM0021 reports a [Mock] and a [TestExport] that name one service on the same method, so the +// export is on the class here. +[SutModule] +[TestExport(typeof(ISingletonService), Implementation = typeof(ExportedSingletonService))] +public partial class MockBeatsTestExportTests +{ + [VerifyTest] + public void TheClassExportApplies(IDependencyOne dependencyOne) + { + Verify(dependencyOne.SingletonService is ExportedSingletonService); + } + + [VerifyTest] + public void AMockBeatsTheExport( + IDependencyOne dependencyOne, + [Mock] ISingletonService singletonService + ) + { + singletonService.GetName().Returns("mocked"); + + Verify(ReferenceEquals(dependencyOne.SingletonService, singletonService)); + Verify(dependencyOne.SingletonService.GetName() == "mocked"); + } +} diff --git a/scripts/coverage.sh b/scripts/coverage.sh index 1852112..6ea7247 100755 --- a/scripts/coverage.sh +++ b/scripts/coverage.sh @@ -50,7 +50,8 @@ for project in "${PROJECTS[@]}"; do done # The VerificationGlue.Tests projects are Microsoft.Testing.Platform applications, which -# coverlet.collector cannot see. The script runs them under coverlet.console and writes their +# coverlet.collector cannot see. The script lists them (tests/DependencyModules.Specs and +# integ-tests/SutProject.VerificationGlueTests), runs them under coverlet.console and writes their # reports under RAW, where the merge below finds them. "${REPO_ROOT}/scripts/test-verificationglue.sh" "${RAW}/verificationglue" diff --git a/scripts/test-verificationglue.sh b/scripts/test-verificationglue.sh index db665cb..0d6f344 100755 --- a/scripts/test-verificationglue.sh +++ b/scripts/test-verificationglue.sh @@ -30,6 +30,7 @@ done PROJECTS=( "tests/DependencyModules.Specs/DependencyModules.Specs.csproj" + "integ-tests/SutProject.VerificationGlueTests/SutProject.VerificationGlueTests.csproj" ) if [ -n "${COVERAGE_DIR}" ]; then diff --git a/scripts/test-xunit.sh b/scripts/test-xunit.sh index 668b1c7..04bd237 100755 --- a/scripts/test-xunit.sh +++ b/scripts/test-xunit.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # -# Runs the xUnit test projects against one xunit.v3 major, and tests/DependencyModules.Specs with -# the DependencyModules.xUnit project of that major. The default build and the coverage script +# Runs the xUnit test projects against one xunit.v3 major, and the VerificationGlue.Tests projects +# of scripts/test-verificationglue.sh, among them tests/DependencyModules.Specs with the +# DependencyModules.xUnit project of that major. The default build and the coverage script # use major 3. CI runs this for 4. # # Usage: diff --git a/tests/DependencyModules.Specs/DependencyModules.Specs.csproj b/tests/DependencyModules.Specs/DependencyModules.Specs.csproj index 4cab500..7df86c4 100644 --- a/tests/DependencyModules.Specs/DependencyModules.Specs.csproj +++ b/tests/DependencyModules.Specs/DependencyModules.Specs.csproj @@ -13,6 +13,11 @@ False true + + false diff --git a/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs b/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs index 39fca13..9f0e8fe 100644 --- a/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/ModuleTestCompositionTests.cs @@ -836,7 +836,9 @@ public static void Resolvable( private sealed class Log : List; - private interface IThing; + // Internal, not private: VerificationGlue.Mocks generates a mock for each [Mock] parameter in + // the assembly, and the generated mock must reach the type. + internal interface IThing; private interface IOther; diff --git a/tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs b/tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs index 146fc71..0bca1bc 100644 --- a/tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/SharedRegistrationsTests.cs @@ -15,7 +15,9 @@ namespace DependencyModules.Specs.TestingTests; /// public partial class SharedRegistrationsTests { - private interface IThing; + // Internal, not private: VerificationGlue.Mocks generates a mock for each [Mock] parameter in + // the assembly, and the generated mock must reach the type. + internal interface IThing; private interface IOther; diff --git a/tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs b/tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs index 868d08a..c6ac3ce 100644 --- a/tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs +++ b/tests/DependencyModules.Specs/TestingTests/TestParameterResolverTests.cs @@ -16,7 +16,9 @@ namespace DependencyModules.Specs.TestingTests; /// public partial class TestParameterResolverTests { - private interface IThing; + // Internal, not private: VerificationGlue.Mocks generates a mock for each [Mock] parameter in + // the assembly, and the generated mock must reach the type. + internal interface IThing; private class Thing : IThing; diff --git a/website/.vitepress/config.ts b/website/.vitepress/config.ts index fb28aa4..3f15c1c 100644 --- a/website/.vitepress/config.ts +++ b/website/.vitepress/config.ts @@ -66,6 +66,7 @@ export default defineConfig({ { text: 'Write tests', link: '/guide/testing' }, { text: 'xUnit', link: '/guide/testing-xunit' }, { text: 'NUnit', link: '/guide/testing-nunit' }, + { text: 'VerificationGlue', link: '/guide/testing-verificationglue' }, { text: 'Mocks', link: '/guide/testing-mocking' }, { text: 'More service providers', link: '/guide/testing-container-source' }, { text: 'CurrentTest and test output', link: '/guide/testing-current-test' }, diff --git a/website/guide/testing-verificationglue.md b/website/guide/testing-verificationglue.md new file mode 100644 index 0000000..310b9cb --- /dev/null +++ b/website/guide/testing-verificationglue.md @@ -0,0 +1,384 @@ +# VerificationGlue + +[VerificationGlue.Tests](https://github.com/ipjohnson/VerificationGlue) gives `[VerifyTest]` tests a service provider from your modules. Put a module attribute on a test class or a test method. No DependencyModules adapter package is necessary. VerificationGlue's generator reads the module attributes and builds the container of each test through `ModuleTestComposition` in `DependencyModules.Testing`. Thus the testing attributes of `DependencyModules.Testing` have the same function as with `DependencyModules.xUnit`. + +The examples on this page come from `integ-tests/SutProject.VerificationGlueTests`. The build workflow runs that project. VerificationGlue documents its own part in [Test a DependencyModules application](https://github.com/ipjohnson/VerificationGlue/blob/main/docs/guide/dependency-modules.md). To move tests from `[ModuleTest]`, refer to [Migrate from DependencyModules.xUnit](https://github.com/ipjohnson/VerificationGlue/blob/main/docs/guide/migrate-from-dependencymodules-xunit.md). + +## Install + +Reference `VerificationGlue.Tests`, `DependencyModules.Runtime`, and `DependencyModules.Testing` 1.8.0 or later. Also reference the project that contains your modules. If the test project declares modules or services, also add `DependencyModules.SourceGenerator`. + +```xml + + net10.0 + + + + + + + + + + + + + + +``` + +`VerificationGlue.Tests` targets `net10.0` only. Do not add `xunit.v3`, `DependencyModules.xUnit`, or a mock package to the same project. A `VerificationGlue.Tests` project is a Microsoft.Testing.Platform application. `dotnet test` needs `"test": { "runner": "Microsoft.Testing.Platform" }` in `global.json`. This repository keeps the VSTest runner for its other test projects, so `scripts/test-verificationglue.sh` runs the built application with `dotnet exec`. + +VerificationGlue.Tests 0.6.0-preview.1 uses a preview of Microsoft.Testing.Platform 3. This repository restores that preview from the `test-tools` feed in `NuGet.config`. + +## Give a test the services of a module + +Put the attribute of a module on the test class. Each test gets a new container with the services of the module, and its parameters come from that container. `[ServiceCollection]` and `[Container]` are not necessary. + +```csharp +[SutModule] +public partial class SimpleResolveTests +{ + [VerifyTest] + public void SimpleTest(IDependencyOne dependencyOne) + { + Verify(dependencyOne is DependencyOne); + Verify(dependencyOne.SingletonService is SingletonService); + Verify(dependencyOne.ScopedService is ScopedService); + } +} +``` + +The test class is `partial`, because VerificationGlue's generator adds to it. A module attribute can be on the assembly, the class, or the method. The modules are applied from the assembly to the class to the method, as with `[ModuleTest]`. + +A module that the test project declares operates the same way: + +```csharp +[SingletonService(Realm = typeof(LocalModule))] +public class Greeter : IGreeter +{ + public string Greet(string name) => $"Hello {name}"; +} + +[DependencyModule(OnlyRealm = true)] +public partial class LocalModule; + +[LocalModule] +public partial class LocalModuleTests +{ + [VerifyTest] + public void AModuleOfTheTestProjectRegistersItsServices(IGreeter greeter) + { + Verify(greeter.Greet("World") == "Hello World"); + } +} +``` + +### Module parameters, realms, and module dependencies + +A module attribute gives its constructor arguments and named properties to the module: + +```csharp +[VerifyTest] +[ParameterizedModule("local-string", 20, C = "CValue")] +public void ConstructorArgumentsAndNamedPropertiesReachTheModule( + SomeRuntimeDependency someRuntimeDependency +) +{ + Verify(someRuntimeDependency.SomeDependency == "local-string"); + Verify(someRuntimeDependency.IntDependency == 20); + Verify(someRuntimeDependency.CValue == "CValue"); +} +``` + +An `OnlyRealm` module registers only the services of its realm. Modules that use each other, such as `ModuleA` with `[ModuleB]` and `ModuleB` with `[ModuleA]`, load both. A module that two attributes name loads one time: + +```csharp +[SutModule] +public partial class ModuleDuplicationTests +{ + [VerifyTest] + [SutModule] + public void AModuleOnTheClassAndTheMethodRegistersOnce(IEnumerable dependencies) + { + Verify(dependencies.Count() == 1); + } +} +``` + +On one class or one method, `DependencyModules.xUnit` and `DependencyModules.NUnit` apply the module attributes of the test assembly after the module attributes of other assemblies. VerificationGlue applies them in the order of the source. When the order of two modules on one target is important, write them in the order that they must load. + +## `[Container]` + +`[Container]` from VerificationGlue can name a module. The container adds the module first, and then the module attributes in scope: + +```csharp +[Container] +public partial class ContainerOfModuleTests +{ + [VerifyTest] + public void TheNamedModuleRegistersItsServices(IDependencyOne dependencyOne) + { + Verify(dependencyOne is DependencyOne); + } + + [VerifyTest] + [ParameterizedModule("method-string", 5, C = "method-c")] + public void TheModuleAttributesInScopeLoadWithIt( + IDependencyOne dependencyOne, + SomeRuntimeDependency dependency + ) + { + Verify(dependencyOne is DependencyOne); + Verify(dependency.SomeDependency == "method-string"); + } +} +``` + +## Mocks + +A `[Mock]` parameter gets a VerificationGlue mock. The mock replaces the registration of its type, so the services of the module get the mock. The next test gets the real service again: + +```csharp +using VerificationGlue.Mocks; + +[SutModule] +public partial class MockTests +{ + [VerifyTest] + public void TheServiceReceivesTheMock( + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + Verify(scopedService is not ScopedService); + } + + [VerifyTest] + public void ATestWithoutTheMockGetsTheRealService(IDependencyOne dependencyOne) + { + Verify(dependencyOne.ScopedService is ScopedService); + Verify(dependencyOne.SingletonService is SingletonService); + } +} +``` + +Set up a mock with `Returns` and examine it with `Received` from `VerificationGlue.Mocks`. `[NSubstituteSupport]`, `[MoqSupport]`, and `[FakeItEasySupport]` do not create the mock of a `[Mock]` parameter. + +A keyed `[Mock]` replaces the registration of its key only: + +```csharp +[KeyedModule] +public partial class KeyedMockTests +{ + [VerifyTest] + public void AKeyedMockReachesTheServiceThatInjectsTheKey( + [Mock] [FromKeyedServices("C")] IKeyedRegistration registration, + CKeyedDependency dependency + ) + { + registration.Key.Returns("mocked"); + + Verify(ReferenceEquals(dependency.Registration, registration)); + Verify(dependency.Registration.Key == "mocked"); + } +} +``` + +`DependencyModules.Testing.Attributes` and `VerificationGlue.Mocks` both declare `MockAttribute`. `VerificationGlue.Tests` adds a global alias of `MockAttribute` to `VerificationGlue.Mocks.MockAttribute`. Thus a file that imports both namespaces can write `[Mock]`: + +```csharp +using DependencyModules.Testing.Attributes; +using VerificationGlue.Mocks; + +[SutModule] +public partial class MockAliasTests +{ + [VerifyTest] + public void MockBindsThroughTheAlias( + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + } +} +``` + +VerificationGlue's generators also read `[DependencyModules.Testing.Attributes.Mock]` as a mock. To turn off the alias, set `VerificationGlueMockAlias` to `false`. Refer to [`[Mock]` from either package](https://github.com/ipjohnson/VerificationGlue/blob/main/docs/guide/dependency-modules.md#mock-from-either-package). + +## `[TestExport]` + +`[TestExport]` registers a service for the tests in its scope. The registration does not continue into the next test: + +```csharp +[SutModule] +public partial class TestExportTests +{ + [VerifyTest] + [TestExport(typeof(ISingletonService), Implementation = typeof(ExportedSingletonService))] + public void OverridesARegistrationForOneTest(ISingletonService singletonService) + { + Verify(singletonService is ExportedSingletonService); + } + + [VerifyTest] + public void TheOverrideDoesNotLeakIntoTheNextTest(ISingletonService singletonService) + { + Verify(singletonService is SingletonService); + } +} +``` + +A `[Mock]` parameter is registered after `[TestExport]`, so the mock replaces the export: + +```csharp +[SutModule] +[TestExport(typeof(ISingletonService), Implementation = typeof(ExportedSingletonService))] +public partial class MockBeatsTestExportTests +{ + [VerifyTest] + public void AMockBeatsTheExport( + IDependencyOne dependencyOne, + [Mock] ISingletonService singletonService + ) + { + singletonService.GetName().Returns("mocked"); + + Verify(ReferenceEquals(dependencyOne.SingletonService, singletonService)); + Verify(dependencyOne.SingletonService.GetName() == "mocked"); + } +} +``` + +DM0021 reports a `[Mock]` parameter and a `[TestExport]` on the same method for the same service. Thus the export in this example is on the class. + +## `[InjectValues]` + +`[InjectValues]` gives constructor arguments to a class that has no registration. The container gives the other arguments: + +```csharp +public record InjectModel(IDependencyOne DependencyOne, string StringValue); + +[SutModule] +public partial class InjectValueTests +{ + [VerifyTest] + public void InjectTestValue([InjectValues("Hello World!")] InjectModel injectModel) + { + Verify(injectModel.DependencyOne is DependencyOne); + Verify(injectModel.StringValue == "Hello World!"); + } +} +``` + +## Environments + +An attribute that implements `IModuleEnvironmentProvider` sets the environment of a test. The narrowest attribute applies: the method, then the class, then the assembly. `[IfEnvironment]` services use that environment: + +```csharp +[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] +public class SeededEnvironmentAttribute(string name) : Attribute, IModuleEnvironmentProvider +{ + public IModuleEnvironment? ProvideEnvironment(MethodInfo testMethod) => + new ModuleEnvironment(false, name); +} + +[SingletonService(Realm = typeof(SeededEnvironmentModule))] +[IfEnvironment("seeded-environment")] +public class GatedByEnvironment : IGatedByEnvironment; + +[DependencyModule(OnlyRealm = true)] +public partial class SeededEnvironmentModule; + +[SeededEnvironmentModule] +[SeededEnvironment("seeded-environment")] +public partial class EnvironmentSeedingPrecedenceTests +{ + [VerifyTest] + public void AClassLevelSeedApplies(IServiceProvider provider) + { + Verify(provider.GetService(typeof(IGatedByEnvironment)) is GatedByEnvironment); + } + + [VerifyTest] + [SeededEnvironment("inner-environment")] + public void TheMethodsSeedBeatsTheClasses( + IServiceProvider provider, + IModuleEnvironment environment + ) + { + Verify(provider.GetService(typeof(IGatedByEnvironment)) is null); + Verify(environment.EnvironmentName == "inner-environment"); + } +} +``` + +For more information, refer to [Environments](./environments.md). + +## `[Shared]` + +`[Container(Scope = ContainerScope.Class)]` builds one container for the class and a child container for each test. A `[Shared]` parameter gets the instance of the class container. The `[Mock]` parameters of a test are registered in the child container of that test, so each test gets its own mock: + +```csharp +[Container(Scope = ContainerScope.Class)] +public partial class SharedTests +{ + private static readonly ConcurrentBag SharedInstances = []; + + private static readonly ConcurrentBag Mocks = []; + + [VerifyTest] + public void FirstTest( + [Shared] ISingletonService shared, + IDependencyOne dependencyOne, + [Mock] IScopedService scopedService + ) + { + SharedInstances.Add(shared); + Mocks.Add(scopedService); + + Verify(SharedInstances.All(seen => ReferenceEquals(seen, shared))); + Verify(Mocks.Count(seen => ReferenceEquals(seen, scopedService)) == 1); + Verify(ReferenceEquals(dependencyOne.ScopedService, scopedService)); + } +} +``` + +`[Shared]` applies to the service type. In the test that has the `[Shared]` parameter, all services of that type come from the class container. A test without `[Shared]` gets an instance of its own child container. + +A container that is shared with `Scope` uses the default environment. VerificationGlue describes this limit in [Environments](https://github.com/ipjohnson/VerificationGlue/blob/main/docs/guide/dependency-modules.md#environments). + +## `CurrentTest` + +`CurrentTest` gives the `[VerifyTest]` test that runs. `Key` is the `TestContext` of the test, and `DisplayName` is its display name: + +```csharp +[SutModule] +public partial class CurrentTestTests +{ + [VerifyTest] + public void KeyIsTheTestContextOfTheRunningTest(TestContext context) + { + Verify(ReferenceEquals(CurrentTest.Key, context)); + } + + [VerifyTest] + public void ALineIsWrittenToTheOutputOfTheTest() + { + Verify(CurrentTest.TryWriteLine("written through CurrentTest")); + } +} +``` + +VerificationGlue builds the container in the test. Thus an `ITestStartupAttribute` sees the test that runs. With `DependencyModules.xUnit`, `CurrentTest` has no test while the container is built. For more information, refer to [`CurrentTest` and test output](./testing-current-test.md). + +## Differences from `DependencyModules.xUnit` + +- A `[Mock]` parameter always gets a VerificationGlue mock. +- `ITestCaseInfo` is not registered. Use a `TestContext` parameter. +- Use `[Row]` and `[RowSource]` from VerificationGlue for data rows. +- On one target, the module attributes are applied in the order of the source. + +[Migrate from DependencyModules.xUnit](https://github.com/ipjohnson/VerificationGlue/blob/main/docs/guide/migrate-from-dependencymodules-xunit.md) gives the complete list. diff --git a/website/guide/testing.md b/website/guide/testing.md index 72294a4..1f12752 100644 --- a/website/guide/testing.md +++ b/website/guide/testing.md @@ -18,6 +18,8 @@ Add one test package to the test project. Also add a reference to the project th For more information about each framework, refer to [xUnit](./testing-xunit.md) and [NUnit](./testing-nunit.md). +`VerificationGlue.Tests` reads module attributes without a DependencyModules test package. It uses `DependencyModules.Testing` to build the container. Refer to [VerificationGlue](./testing-verificationglue.md). + ## Write a test Replace `[Fact]` or `[Test]` with `[ModuleTest]`. Give the module types to the attribute. Declare a parameter for each service that the test uses.