diff --git a/Docs/pages/04-create-mocks.md b/Docs/pages/04-create-mocks.md index 59ef7bc6..f252805d 100644 --- a/Docs/pages/04-create-mocks.md +++ b/Docs/pages/04-create-mocks.md @@ -142,6 +142,7 @@ When no setup matches, the mock returns: - an empty string for `string`, - a completed task for `Task`, `Task`, `ValueTask` and `ValueTask`, - a tuple with recursively defaulted values for tuples, +- a function that returns its argument for `Func` and an action that does nothing for `Action`, so that an options callback like `Func` keeps the default options, - `default(T)` for value types and `null` for other reference types. You can register custom factories per type using `.WithDefaultValueFor()`: @@ -395,7 +396,7 @@ Every constructor parameter gets an argument, by the first rule that applies: - A **mockable interface** gets a new mock with the same behavior, even when the parameter is optional or nullable. - A **`params` parameter** gets an empty collection, and an **optional parameter** its declared default value. - A **nullable parameter** gets `null`. -- **Any other parameter** gets a value from the [default values](#default-values) of the behavior: a value registered with `WithDefaultValueFor` or a default value generator, for example one backed by a library like AutoFixture, and otherwise `""` for a `string`, an empty collection or the default of a value type. Without a value for a reference type, the creation fails with a `MockException`. +- **Any other parameter** gets a value from the [default values](#default-values) of the behavior: a value registered with `WithDefaultValueFor` or a default value generator, for example one backed by a library like AutoFixture, and otherwise `""` for a `string`, an empty collection, a callback that keeps the options for `Func` or `Action`, or the default of a value type. Without a value for a reference type, the creation fails with a `MockException`. `ConstructorArgument()` returns the argument of the parameter declared with type `T`, or else the only argument that converts to `T`. When several match, pass the name of the parameter: `sut.Mock.ConstructorArgument("source")`. diff --git a/Source/Mockolate.SourceGenerators/Sources/Sources.MockBehaviorExtensions.cs b/Source/Mockolate.SourceGenerators/Sources/Sources.MockBehaviorExtensions.cs index d1e2ead9..f991a0a7 100644 --- a/Source/Mockolate.SourceGenerators/Sources/Sources.MockBehaviorExtensions.cs +++ b/Source/Mockolate.SourceGenerators/Sources/Sources.MockBehaviorExtensions.cs @@ -42,7 +42,8 @@ static Mock() /// /// /// Un-configured members return the generator-provided default value (empty strings/collections, completed - /// s, otherwise), base-class + /// s, an identity + /// for Func<T, T>, a no-op , otherwise), base-class /// implementations run for class mocks, and every invocation is recorded for later verification. /// /// Chain SkippingBaseClass(), ThrowingWhenNotSetup(), SkippingInteractionRecording(), @@ -453,6 +454,34 @@ public T[] Generate(T[] nullValue, params object?[] parameters) public T[,,,] Generate(T[,,,] nullValue, params object?[] parameters) => new T[,,,] { }; + /// + /// Generates a function that returns its argument, such as an options callback, with + /// the for context. + /// + public global::System.Func Generate(global::System.Func nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Func), parameters) is global::System.Func value) + { + return value; + } + + return static argument => argument; + } + + /// + /// Generates an action that does nothing, such as a configure callback, with + /// the for context. + /// + public global::System.Action Generate(global::System.Action nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Action), parameters) is global::System.Action value) + { + return value; + } + + return static _ => { }; + } + """).AppendLine(); if (includeAsyncEnumerable) { diff --git a/Tests/Frameworks/Mockolate.Frameworks.TestHelpers/Domain/ChocolateFactory.cs b/Tests/Frameworks/Mockolate.Frameworks.TestHelpers/Domain/ChocolateFactory.cs new file mode 100644 index 00000000..eed94d0a --- /dev/null +++ b/Tests/Frameworks/Mockolate.Frameworks.TestHelpers/Domain/ChocolateFactory.cs @@ -0,0 +1,22 @@ +using System; + +namespace Mockolate.Frameworks.TestHelpers.Domain; + +public sealed class ChocolateFactory +{ + public ChocolateFactory() : this(o => o, _ => { }) { } + + public ChocolateFactory(Func options, + Action configure) + { + Options = options(new ChocolateFactoryOptions()); + configure(Options); + } + + public ChocolateFactoryOptions Options { get; } +} + +public sealed class ChocolateFactoryOptions +{ + public string Flavor { get; set; } = "Dark"; +} diff --git a/Tests/Frameworks/Mockolate.TUnit.Tests/AutoMockArgumentsTests.cs b/Tests/Frameworks/Mockolate.TUnit.Tests/AutoMockArgumentsTests.cs index c9450f37..8ad71b56 100644 --- a/Tests/Frameworks/Mockolate.TUnit.Tests/AutoMockArgumentsTests.cs +++ b/Tests/Frameworks/Mockolate.TUnit.Tests/AutoMockArgumentsTests.cs @@ -149,6 +149,11 @@ public async Task AutoMockArguments_WithTransientParameter_ShouldNotShareItWithT await That(shippingClient.Mock.Verify.Ship(order)).Never(); } + [Test] + [AutoMockArguments] + public async Task AutoMockArguments_WithOptionsDelegates_ShouldUseTheDefaultOptions(ChocolateFactory sut) + => await That(sut.Options.Flavor).IsEqualTo("Dark"); + [Test] [AutoMockArguments] public async Task AutoMockArguments_WithSeveralParametersOfTheType_ShouldMatchThemByName(TransferService sut, diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.AutoMock_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.AutoMock_CanBeCreated.g.awexpect-snapshot.cs index c697fa8c..41bcb1de 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.AutoMock_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.AutoMock_CanBeCreated.g.awexpect-snapshot.cs @@ -30,7 +30,8 @@ static Mock() /// /// /// Un-configured members return the generator-provided default value (empty strings/collections, completed - /// Tasks, otherwise), base-class + /// Tasks, an identity Func<T, TResult> + /// for Func<T, T>, a no-op Action<T>, otherwise), base-class /// implementations run for class mocks, and every invocation is recorded for later verification. /// /// Chain SkippingBaseClass(), ThrowingWhenNotSetup(), SkippingInteractionRecording(), @@ -394,6 +395,34 @@ public T[] Generate(T[] nullValue, params object?[] parameters) public T[,,,] Generate(T[,,,] nullValue, params object?[] parameters) => new T[,,,] { }; + /// + /// Generates a function that returns its argument, such as an options callback, with + /// the for context. + /// + public global::System.Func Generate(global::System.Func nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Func), parameters) is global::System.Func value) + { + return value; + } + + return static argument => argument; + } + + /// + /// Generates an action that does nothing, such as a configure callback, with + /// the for context. + /// + public global::System.Action Generate(global::System.Action nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Action), parameters) is global::System.Action value) + { + return value; + } + + return static _ => { }; + } + /// /// Generates an empty async enumerable of , with /// the for context. diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.BaseClass_WithMultipleAdditionalInterfaces_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.BaseClass_WithMultipleAdditionalInterfaces_CanBeCreated.g.awexpect-snapshot.cs index a6073144..c7d4c53d 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.BaseClass_WithMultipleAdditionalInterfaces_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.BaseClass_WithMultipleAdditionalInterfaces_CanBeCreated.g.awexpect-snapshot.cs @@ -30,7 +30,8 @@ static Mock() /// /// /// Un-configured members return the generator-provided default value (empty strings/collections, completed - /// Tasks, otherwise), base-class + /// Tasks, an identity Func<T, TResult> + /// for Func<T, T>, a no-op Action<T>, otherwise), base-class /// implementations run for class mocks, and every invocation is recorded for later verification. /// /// Chain SkippingBaseClass(), ThrowingWhenNotSetup(), SkippingInteractionRecording(), @@ -370,6 +371,34 @@ public T[] Generate(T[] nullValue, params object?[] parameters) public T[,,,] Generate(T[,,,] nullValue, params object?[] parameters) => new T[,,,] { }; + /// + /// Generates a function that returns its argument, such as an options callback, with + /// the for context. + /// + public global::System.Func Generate(global::System.Func nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Func), parameters) is global::System.Func value) + { + return value; + } + + return static argument => argument; + } + + /// + /// Generates an action that does nothing, such as a configure callback, with + /// the for context. + /// + public global::System.Action Generate(global::System.Action nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Action), parameters) is global::System.Action value) + { + return value; + } + + return static _ => { }; + } + /// /// Generates an empty async enumerable of , with /// the for context. diff --git a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.HttpClient_CanBeCreated.g.awexpect-snapshot.cs b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.HttpClient_CanBeCreated.g.awexpect-snapshot.cs index defe6cd9..eb83fade 100644 --- a/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.HttpClient_CanBeCreated.g.awexpect-snapshot.cs +++ b/Tests/Mockolate.SourceGenerators.Tests/Snapshot/MockGenerationSnapshotTests/GeneratorOutput_MatchesExpectedSnapshot/MockBehaviorExtensions.HttpClient_CanBeCreated.g.awexpect-snapshot.cs @@ -30,7 +30,8 @@ static Mock() /// /// /// Un-configured members return the generator-provided default value (empty strings/collections, completed - /// Tasks, otherwise), base-class + /// Tasks, an identity Func<T, TResult> + /// for Func<T, T>, a no-op Action<T>, otherwise), base-class /// implementations run for class mocks, and every invocation is recorded for later verification. /// /// Chain SkippingBaseClass(), ThrowingWhenNotSetup(), SkippingInteractionRecording(), @@ -387,6 +388,34 @@ public T[] Generate(T[] nullValue, params object?[] parameters) public T[,,,] Generate(T[,,,] nullValue, params object?[] parameters) => new T[,,,] { }; + /// + /// Generates a function that returns its argument, such as an options callback, with + /// the for context. + /// + public global::System.Func Generate(global::System.Func nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Func), parameters) is global::System.Func value) + { + return value; + } + + return static argument => argument; + } + + /// + /// Generates an action that does nothing, such as a configure callback, with + /// the for context. + /// + public global::System.Action Generate(global::System.Action nullValue, params object?[] parameters) + { + if (generator.GenerateValue(typeof(global::System.Action), parameters) is global::System.Action value) + { + return value; + } + + return static _ => { }; + } + /// /// Generates an empty async enumerable of , with /// the for context. diff --git a/Tests/Mockolate.Tests/MockBehaviorTests.DefaultValueTests.cs b/Tests/Mockolate.Tests/MockBehaviorTests.DefaultValueTests.cs index 96965cfc..c7fdc10e 100644 --- a/Tests/Mockolate.Tests/MockBehaviorTests.DefaultValueTests.cs +++ b/Tests/Mockolate.Tests/MockBehaviorTests.DefaultValueTests.cs @@ -52,6 +52,49 @@ public async Task WithCombination_ShouldReturnNotNullValues() await That(result.Item3).IsEqualTo(""); } + [Test] + public async Task WithAction_ShouldReturnActionThatDoesNothing() + { + IDefaultValueGeneratorProperties sut = IDefaultValueGeneratorProperties.CreateMock(); + + Action> result = sut.Configure; + + List values = [1,]; + result(values); + await That(values).IsEqualTo([1,]); + } + + [Test] + public async Task WithFuncReturningItsArgumentType_ShouldReturnTheArgument() + { + IDefaultValueGeneratorProperties sut = IDefaultValueGeneratorProperties.CreateMock(); + + Func result = sut.Options; + + await That(result("foo")).IsEqualTo("foo"); + } + + [Test] + public async Task WithFuncReturningItsArgumentType_WhenRegistered_ShouldReturnTheRegisteredValue() + { + Func registered = value => value + "bar"; + MockBehavior sut = MockBehavior.Default.WithDefaultValueFor(() => registered); + + Func result = sut.DefaultValue.Generate(default(Func)!); + + await That(result).IsSameAs(registered); + } + + [Test] + public async Task WithFuncReturningOtherType_ShouldReturnNull() + { + MockBehavior sut = MockBehavior.Default; + + Func result = sut.DefaultValue.Generate(default(Func)!); + + await That(result).IsNull(); + } + [Test] public async Task WithHttpResponseMessage_ShouldReturnEmptyResponseWithNotImplementedStatusCode() { @@ -246,6 +289,8 @@ public interface IDefaultValueGeneratorProperties ValueTask IntArrayValueTask { get; } IMyRecursiveService RecursiveService { get; } HttpResponseMessage HttpResponseMessage { get; } + Func Options { get; } + Action> Configure { get; } Task<(int, int[], string)> ComplexTask(); Type GetMyType();