Skip to content

Commit 7adc134

Browse files
authored
Handle open generics for SkipTypeMockHandler (#58)
1 parent 930441d commit 7adc134

File tree

2 files changed

+25
-7
lines changed

2 files changed

+25
-7
lines changed

AutofacContrib.NSubstitute.Tests/TypesToSkipForMockingFixture.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,19 @@ public void ManuallyCheckTypeToSkip()
5151
Assert.Throws<ComponentNotRegisteredException>(() => mock.Resolve<IDependency>());
5252
}
5353

54+
[Test]
55+
public void ManuallyCheckTypeToSkipOpenGeneric()
56+
{
57+
var mock = AutoSubstitute.Configure()
58+
.ConfigureOptions(options =>
59+
{
60+
options.MockHandlers.Add(SkipTypeMockHandler.Create(typeof(IDependency<>)));
61+
})
62+
.Build();
63+
64+
Assert.Throws<ComponentNotRegisteredException>(() => mock.Resolve<IDependency<object>>());
65+
}
66+
5467
[Test]
5568
public void RegisteredTypesAreNotMocked()
5669
{
@@ -68,6 +81,10 @@ public interface IDependency
6881
{
6982
}
7083

84+
public interface IDependency<T>
85+
{
86+
}
87+
7188
public class Impl1 : IDependency
7289
{
7390
}

AutofacContrib.NSubstitute/MockHandlers/SkipTypeMockHandler.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
namespace AutofacContrib.NSubstitute.MockHandlers
77
{
88
/// <summary>
9-
/// An implementation of a <see cref="MockHandler"/> that will skip creation of mocks of type <typeparamref name="T"/>.
9+
/// An implementation of a <see cref="MockHandler"/> that will skip creation of mocks for given types.
1010
/// </summary>
11-
public class SkipTypeMockHandler : MockHandler
11+
public sealed class SkipTypeMockHandler : MockHandler
1212
{
1313
private readonly IEnumerable<Type> _types;
1414

@@ -34,17 +34,18 @@ public class SkipTypeMockHandler : MockHandler
3434

3535
private SkipTypeMockHandler(IEnumerable<Type> types)
3636
{
37-
_types = types;
37+
_types = types ?? throw new ArgumentNullException(nameof(types));
3838
}
3939

40-
protected internal sealed override void OnMockCreated(object instance, Type type, IComponentContext context, ISubstitutionContext substitutionContext)
41-
=> base.OnMockCreated(instance, type, context, substitutionContext);
42-
4340
protected internal override void OnMockCreating(MockCreatingContext context)
4441
{
4542
foreach (var type in _types)
4643
{
47-
if (type == context.Type)
44+
if (type.IsGenericType && type == type.GetGenericTypeDefinition())
45+
{
46+
context.DoNotCreate();
47+
}
48+
else if (type == context.Type)
4849
{
4950
context.DoNotCreate();
5051
}

0 commit comments

Comments
 (0)