Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Docs/pages/04-create-mocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ When no setup matches, the mock returns:
- an empty string for `string`,
- a completed task for `Task`, `Task<T>`, `ValueTask` and `ValueTask<T>`,
- a tuple with recursively defaulted values for tuples,
- a function that returns its argument for `Func<T, T>` and an action that does nothing for `Action<T>`, so that an options callback like `Func<ChocolateOptions, ChocolateOptions>` keeps the default options,
- `default(T)` for value types and `null` for other reference types.

You can register custom factories per type using `.WithDefaultValueFor<T>()`:
Expand Down Expand Up @@ -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<T, T>` or `Action<T>`, or the default of a value type. Without a value for a reference type, the creation fails with a `MockException`.

`ConstructorArgument<T>()` 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<IChocolateDispenser>("source")`.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ static Mock()
/// </summary>
/// <remarks>
/// Un-configured members return the generator-provided default value (empty strings/collections, completed
/// <see cref="global::System.Threading.Tasks.Task" />s, <see langword="null" /> otherwise), base-class
/// <see cref="global::System.Threading.Tasks.Task" />s, an identity <see cref="global::System.Func{T, TResult}" />
/// for <c>Func&lt;T, T&gt;</c>, a no-op <see cref="global::System.Action{T}" />, <see langword="null" /> otherwise), base-class
/// implementations run for class mocks, and every invocation is recorded for later verification.
/// <para />
/// Chain <c>SkippingBaseClass()</c>, <c>ThrowingWhenNotSetup()</c>, <c>SkippingInteractionRecording()</c>,
Expand Down Expand Up @@ -453,6 +454,34 @@ public T[] Generate<T>(T[] nullValue, params object?[] parameters)
public T[,,,] Generate<T>(T[,,,] nullValue, params object?[] parameters)
=> new T[,,,] { };

/// <summary>
/// Generates a function that returns its argument, such as an options callback, with
/// the <paramref name="parameters" /> for context.
/// </summary>
public global::System.Func<T, T> Generate<T>(global::System.Func<T, T> nullValue, params object?[] parameters)
{
if (generator.GenerateValue(typeof(global::System.Func<T, T>), parameters) is global::System.Func<T, T> value)
{
return value;
}

return static argument => argument;
}

/// <summary>
/// Generates an action that does nothing, such as a configure callback, with
/// the <paramref name="parameters" /> for context.
/// </summary>
public global::System.Action<T> Generate<T>(global::System.Action<T> nullValue, params object?[] parameters)
{
if (generator.GenerateValue(typeof(global::System.Action<T>), parameters) is global::System.Action<T> value)
{
return value;
}

return static _ => { };
}

""").AppendLine();
if (includeAsyncEnumerable)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;

namespace Mockolate.Frameworks.TestHelpers.Domain;

public sealed class ChocolateFactory
{
public ChocolateFactory() : this(o => o, _ => { }) { }

public ChocolateFactory(Func<ChocolateFactoryOptions, ChocolateFactoryOptions> options,
Action<ChocolateFactoryOptions> configure)
{
Options = options(new ChocolateFactoryOptions());
configure(Options);
}

public ChocolateFactoryOptions Options { get; }
}

public sealed class ChocolateFactoryOptions
{
public string Flavor { get; set; } = "Dark";
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

45 changes: 45 additions & 0 deletions Tests/Mockolate.Tests/MockBehaviorTests.DefaultValueTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<List<int>> result = sut.Configure;

List<int> values = [1,];
result(values);
await That(values).IsEqualTo([1,]);
}

[Test]
public async Task WithFuncReturningItsArgumentType_ShouldReturnTheArgument()
{
IDefaultValueGeneratorProperties sut = IDefaultValueGeneratorProperties.CreateMock();

Func<string, string> result = sut.Options;

await That(result("foo")).IsEqualTo("foo");
}

[Test]
public async Task WithFuncReturningItsArgumentType_WhenRegistered_ShouldReturnTheRegisteredValue()
{
Func<string, string> registered = value => value + "bar";
MockBehavior sut = MockBehavior.Default.WithDefaultValueFor(() => registered);

Func<string, string> result = sut.DefaultValue.Generate(default(Func<string, string>)!);

await That(result).IsSameAs(registered);
}

[Test]
public async Task WithFuncReturningOtherType_ShouldReturnNull()
{
MockBehavior sut = MockBehavior.Default;

Func<string, int> result = sut.DefaultValue.Generate(default(Func<string, int>)!);

await That(result).IsNull();
}

[Test]
public async Task WithHttpResponseMessage_ShouldReturnEmptyResponseWithNotImplementedStatusCode()
{
Expand Down Expand Up @@ -246,6 +289,8 @@ public interface IDefaultValueGeneratorProperties
ValueTask<int[]> IntArrayValueTask { get; }
IMyRecursiveService RecursiveService { get; }
HttpResponseMessage HttpResponseMessage { get; }
Func<string, string> Options { get; }
Action<List<int>> Configure { get; }

Task<(int, int[], string)> ComplexTask();
Type GetMyType();
Expand Down
Loading