Skip to content

Commit

Permalink
Implement System.IServiceProvider in AutoMocker. (#128)
Browse files Browse the repository at this point in the history
* #127 - Implement `System.IServiceProvider` in `AutoMocker`.

* Add tests

Co-authored-by: Kevin B <Keboo@users.noreply.github.com>
  • Loading branch information
ascott18 and Keboo committed Oct 25, 2021
1 parent 534fabb commit d4bc4dd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
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

0 comments on commit d4bc4dd

Please sign in to comment.