Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement System.IServiceProvider in AutoMocker. #128

Merged
merged 3 commits into from
Oct 25, 2021
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
17 changes: 17 additions & 0 deletions Moq.AutoMock.Tests/DescribeGetMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,22 @@ public void It_allows_getting_mocked_object_when_overriden()
Assert.IsNotNull(@protected);
Assert.IsInstanceOfType(@protected, typeof(ProtectedConstructor1));
}

[TestMethod]
public void It_gets_mocked_object_via_iserviceprovider()
{
IServiceProvider mocker = new AutoMocker();
var service = mocker.GetService(typeof(Empty));
Assert.IsNotNull(service);
Assert.IsInstanceOfType(service, typeof(Empty));
}

[TestMethod]
public void It_returns_null_for_unmockable_object_via_iserviceprovider()
{
IServiceProvider mocker = new AutoMocker();
var service = mocker.GetService(typeof(string));
Assert.IsNull(service);
}
}
}
10 changes: 9 additions & 1 deletion Moq.AutoMock/AutoMocker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ namespace Moq.AutoMock
/// <summary>
/// An auto-mocking IoC container that generates mock objects using Moq.
/// </summary>
public partial class AutoMocker
public partial class AutoMocker : IServiceProvider
{
/// <summary>
/// Initializes an instance of AutoMockers.
Expand Down Expand Up @@ -441,6 +441,14 @@ internal bool TryGet(
return false;
}

/// <inheritdoc />
object? IServiceProvider.GetService(Type serviceType)
{
return TryGet(serviceType, new ObjectGraphContext(false), out IInstance? service)
? service.Value
: null;
}

#endregion Get

#region GetMock
Expand Down