8000 Allow `DefaultValue.Mock` to mock `Task<TMockable>` and `ValueTask<TMockable>` by stakx · Pull Request #502 · devlooped/moq · GitHub
[go: up one dir, main page]

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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ The format is loosely based on [Keep a Changelog](http://keepachangelog.com/en/1
* Support for `ValueTask<TResult>` when using the `ReturnsAsync` extension methods, similar to `Task<TResult>` (@AdamDotNet, #506)
* Special handling for `ValueTask<TResult>` with `DefaultValue.Empty` (@stakx, #529)
* Support for custom default value generators (besides `DefaultValue.Empty` and `DefaultValue.Mock`): subclass the new `DefaultValueProvider` and set up via `Mock[Repository].DefaultValueProvider` (@stakx, #533)
* Allow `DefaultValue.Mock` to mock `Task<TMockable>` and `ValueTask<TMockable>` (@stakx, #502)

#### Changed

Expand Down
157 changes: 153 additions & 4 deletions Moq.Tests/MockDefaultValueProviderFixture.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
#if NETCORE
using System.Reflection;
#endif
using System.Threading.Tasks;

using Xunit;

namespace Moq.Tests
Expand Down Expand Up @@ -104,6 +104,145 @@ public void Inner_mocks_inherit_switches_of_parent_mock()
Assert.Equal(expectedSwitches, actual: innerMock.Switches);
}

[Fact]
public void Provides_completed_Task_containing_default_value_for_Task_of_value_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (Task<int>)GetDefaultValueForProperty(nameof(IFoo.TaskOfValueType), mock);

Assert.NotNull(task);
Assert.True(task.IsCompleted);
Assert.Equal(default(int), task.Result);
}

[Fact]
public void Provides_completed_Task_containing_empty_value_for_Task_of_emptyable_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (Task<int[]>)GetDefaultValueForProperty(nameof(IFoo.TaskOfEmptyableType), mock);

Assert.NotNull(task);
Assert.True(task.IsCompleted);
Assert.NotNull(task.Result);
Assert.Empty(task.Result);
}

[Fact]
public void Provides_completed_Task_containing_null_for_Task_of_unmockable_reference_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (Task<IndexOutOfRangeException>)GetDefaultValueForProperty(nameof(IFoo.TaskOfUnmockableReferenceType), mock);

Assert.NotNull(task);
Assert.True(task.IsCompleted);
Assert.Null(task.Result);
}

[Fact]
public void Provides_completed_Task_containing_mocked_value_for_Task_of_mockable_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (Task<IBar>)GetDefaultValueForProperty(nameof(IFoo.TaskOfMockableType), mock);

Assert.NotNull(task);
Assert.True(task.IsCompleted);
Assert.NotNull(task.Result);
Assert.True(task.Result is IMocked);
}

[Fact]
public void Provides_completed_Task_containing_completed_Task_containing_whatever_for_Task_of_Task_of_whatever()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (Task<Task<int>>)GetDefaultValueForProperty(nameof(IFoo.TaskOfTaskOfWhatever), mock);

Assert.NotNull(task);
Assert.True(task.IsCompleted);
Assert.NotNull(task.Result);
Assert.True(task.Result.IsCompleted);
}

[Fact]
public void Provides_completed_ValueTask_containing_default_value_for_ValueTask_of_value_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (ValueTask<int>)GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfValueType), mock);

Assert.True(task.IsCompleted);
Assert.Equal(default(int), task.Result);
}

[Fact]
public void Provides_completed_ValueTask_containing_empty_value_for_ValueTask_of_emptyable_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (ValueTask<int[]>)GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfEmptyableType), mock);

Assert.True(task.IsCompleted);
Assert.NotNull(task.Result);
Assert.Empty(task.Result);
}

[Fact]
public void Provides_completed_ValueTask_containing_null_for_Task_of_unmockable_reference_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (ValueTask<IndexOutOfRangeException>)GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfUnmockableReferenceType), mock);

Assert.True(task.IsCompleted);
Assert.Null(task.Result);
}

[Fact]
public void Provides_completed_ValueTask_containing_mocked_value_for_ValueTask_of_mockable_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (ValueTask<IBar>)GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfMockableType), mock);

Assert.True(task.IsCompleted);
Assert.NotNull(task.Result);
Assert.True(task.Result is IMocked);
}

[Fact]
public void Provides_completed_ValueTask_of_completed_Task_of_mocked_value_for_ValueTask_of_Task_of_mockable_type()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };
var task = (ValueTask<Task<IBar>>)GetDefaultValueForProperty(nameof(IFoo.ValueTaskOfTaskOfMockableType), mock);

Assert.True(task.IsCompleted);
Assert.NotNull(task.Result);
Assert.True(task.Result.IsCompleted);
Assert.NotNull(task.Result.Result);
Assert.True(task.Result.Result is IMocked);
}

[Fact]
public async Task Mock_wrapped_in_completed_Task_gets_included_in_verification_of_outer_mock()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };

var bar = await mock.Object.TaskOfMockableType;
var barMock = Mock.Get(bar);
barMock.Setup(b => b.Do()).Verifiable();

var ex = Assert.Throws<MockException>(() => mock.Verify());
Assert.True(ex.IsVerificationError);
}

[Fact]
public async Task Mock_wrapped_in_completed_ValueTask_gets_included_in_verification_of_outer_mock()
{
var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock };

var bar = await mock.Object.ValueTaskOfMockableType;
var barMock = Mock.Get(bar);
barMock.Setup(b => b.Do()).Verifiable();

var ex = Assert.Throws<MockException>(() => mock.Verify());
Assert.True(ex.IsVerificationError);
}

private static object GetDefaultValueForProperty(string propertyName, Mock<IFoo> mock)
{
var propertyGetter = typeof(IFoo).GetProperty(propertyName).GetGetMethod();
Expand All @@ -116,6 +255,16 @@ public interface IFoo
string Value { get; set; }
IEnumerable<int> Indexes { get; set; }
IBar[] Bars { get; set; }
Task<int> TaskOfValueType { get; set; }
Task<int[]> TaskOfEmptyableType { get; set; }
Task<IndexOutOfRangeException> TaskOfUnmockableReferenceType { get; set; }
Task<IBar> TaskOfMockableType { get; set; }
Task<Task<int>> TaskOfTaskOfWhatever { get; set; }
ValueTask<int> ValueTaskOfValueType { get; set; }
ValueTask<int[]> ValueTaskOfEmptyableType { get; set; }
ValueTask<IndexOutOfRangeException> ValueTaskOfUnmockableReferenceType { get; set; }
ValueTask<IBar> ValueTaskOfMockableType { get; set; }
ValueTask<Task<IBar>> ValueTaskOfTaskOfMockableType { get; set; }
}

public interface IBar { void Do(); }
Expand Down
2 changes: 1 addition & 1 deletion Source/AsInterface.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public AsInterface(Mock owner)

internal override Dictionary<Type, object> ConfiguredDefaultValues => this.owner.ConfiguredDefaultValues;

internal override ConcurrentDictionary<MethodInfo, Mock> InnerMocks
internal override ConcurrentDictionary<MethodInfo, MockWithWrappedMockObject> InnerMocks
{
get { return this.owner.InnerMocks; }
}
Expand Down
4 changes: 2 additions & 2 deletions Source/InterceptorStrategies.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,10 +153,10 @@ public InterceptionAction HandleIntercept(ICallContext invocation, Mock mock)

if (invocation.Method.ReturnType != typeof(void))
{
Mock recursiveMock;
MockWithWrappedMockObject recursiveMock;
if (mock.InnerMocks.TryGetValue(invocation.Method, out recursiveMock))
{
invocation.ReturnValue = recursiveMock.Object;
invocation.ReturnValue = recursiveMock.WrappedMockObject;
}
else
{
Expand Down
19 changes: 16 additions & 3 deletions Source/Linq/Mocks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

using Moq.Linq;
using Moq.Properties;

Expand Down Expand Up @@ -200,13 +200,26 @@ public static Mock<TResult> FluentMock<T, TResult>(this Mock<T> mock, Expression
info.ReturnType.ThrowIfNotMockeable();

Mock fluentMock;
if (!mock.InnerMocks.TryGetValue(info, out fluentMock))
MockWithWrappedMockObject innerMock;
if (mock.InnerMocks.TryGetValue(info, out innerMock))
{
fluentMock = innerMock.Mock;
}
else
{
fluentMock = ((IMocked)mock.GetDefaultValue(info, useAlternateProvider: MockDefaultValueProvider.Instance)).Mock;
Mock.SetupAllProperties(fluentMock);

innerMock = new MockWithWrappedMockObject(fluentMock, fluentMock.Object);
// ^^^^^^^^^^^^^^^^^
// NOTE: Above, we are assuming that a default value was returned that is neither a `Task<T>` nor a `ValueTask<T>`,
// i.e. nothing we'd need to first "unwrap" to get at the actual mocked object. This assumption would seem permissible
// since the present method gets called only for multi-dot expressions ("recursive mocking"), which do not allow
// `await` expressions. Therefore we don't need to deal with `Task<T>` nor `ValueTask<T>`, and we proceed as if the
// returned default value were already "unwrapped".
}

var result = (TResult)fluentMock.Object;
var result = (TResult)innerMock.WrappedMockObject;

mock.Setup(setup).Returns(result);

Expand Down
42 changes: 36 additions & 6 deletions Source/Mock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

using Moq.Diagnostics.Errors;
using Moq.Language.Flow;
Expand All @@ -72,7 +73,7 @@ protected Mock()
{
this.eventHandlers = new EventHandlerCollection();
this.ImplementedInterfaces = new List<Type>();
this.InnerMocks = new ConcurrentDictionary<MethodInfo, Mock>();
this.InnerMocks = new ConcurrentDictionary<MethodInfo, MockWithWrappedMockObject>();
this.invocations = new InvocationCollection();
this.setups = new SetupCollection();
this.switches = Switches.Default;
Expand Down Expand Up @@ -200,7 +201,7 @@ private object GetObject()
return value;
}

internal virtual ConcurrentDictionary<MethodInfo, Mock> InnerMocks { get; private set; }
internal virtual ConcurrentDictionary<MethodInfo, MockWithWrappedMockObject> InnerMocks { get; private set; }

internal virtual InvocationCollection Invocations => this.invocations;

Expand Down Expand Up @@ -281,7 +282,7 @@ private bool TryVerify(out UnmatchedSetups error)

foreach (var inner in this.InnerMocks.Values)
{
if (!inner.TryVerify(out error))
if (!inner.Mock.TryVerify(out error))
{
return false;
}
Expand Down Expand Up @@ -311,7 +312,7 @@ private bool TryVerifyAll(out UnmatchedSetups error)

foreach (var inner in this.InnerMocks.Values)
{
if (!inner.TryVerifyAll(out error))
if (!inner.Mock.TryVerifyAll(out error))
{
return false;
}
Expand Down Expand Up @@ -1206,8 +1207,9 @@ internal object GetDefaultValue(MethodInfo method, DefaultValueProvider useAlter
}

var result = (useAlternateProvider ?? this.DefaultValueProvider).GetDefaultReturnValue(method, this);
var unwrappedResult = TryUnwrapResultFromCompletedTaskRecursively(result);
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the standard default value providers (Empty and Mock), it would be great if the wrapping (inside the provider) and unwrapping (here) could be avoided. It should be possible to add a fast path as follows:

  1. Check whether this.DefaultValue != DefaultValue.Custom. If false, stop.
  2. Check whether method returns a task. If so, ask the provider not for the actual task return type via GetDefaultReturnValue, but for the type of the wrapped value via GetDefaultValue.
  3. Perform the wrapping into completed tasks here, given the value returned from the provider.

This would save us one unnecessary recursive task unwrapping operation.


if (result is IMocked mockedResult)
if (unwrappedResult is IMocked unwrappedMockedResult)
{
// TODO: Perhaps the following `InnerMocks` update isn't in quite the right place yet.
// There are two main places in Moq where `InnerMocks` are used: `Mock<T>.FluentMock` and
Expand All @@ -1217,12 +1219,40 @@ internal object GetDefaultValue(MethodInfo method, DefaultValueProvider useAlter
// code locations and therefore non-atomic. It would be good if those could be combined
// (`InnerMocks.GetOrAdd`), but that might not be easily possible since `InnerMocks` is
// only mocks while default value providers can also return plain, unmocked values.
this.InnerMocks.TryAdd(method, mockedResult.Mock);
this.InnerMocks.TryAdd(method, new MockWithWrappedMockObject(unwrappedMockedResult.Mock, result));
}

return result;
}

/// <summary>
/// Recursively unwraps the result from completed <see cref="Task{TResult}"/> or <see cref="ValueTask{TResult}"/> instances.
/// If the given value is not a task, the value itself is returned.
/// </summary>
/// <param name="obj">The value to be unwrapped.</param>
private static object TryUnwrapResultFromCompletedTaskRecursively(object obj)
{
if (obj != null)
{
var objType = obj.GetType();
if (objType.GetTypeInfo().IsGenericType)
{
var genericTypeDefinition = objType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Task<>) || genericTypeDefinition == typeof(ValueTask<>))
{
var isCompleted = (bool)objType.GetProperty("IsCompleted").GetValue(obj, null);
if (isCompleted)
{
var innerObj = objType.GetProperty("Result").GetValue(obj, null);
return TryUnwrapResultFromCompletedTaskRecursively(innerObj);
}
}
}
}

return obj;
}

#endregion
}
}
Loading
0