Skip to content

Commit a55cd23

Browse files
authored
Only resolve properties on substitutes that can be resolved (#51)
1 parent 3f4264d commit a55cd23

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

AutofacContrib.NSubstitute.Tests/AutoSubstituteOptionsFixture.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Autofac;
22
using Autofac.Core;
3+
using Autofac.Core.Registration;
34
using NUnit.Framework;
45
using System;
56

@@ -74,6 +75,23 @@ public void InjectPropertiesClass()
7475
Assert.IsNotNull(obj.Service);
7576
}
7677

78+
[Test]
79+
public void InjectPropertiesNotResolvable()
80+
{
81+
using var mock = AutoSubstitute.Configure()
82+
.InjectProperties()
83+
.SubstituteFor<WithStringProperty>()
84+
.Build()
85+
.Container;
86+
87+
// Verify that strings are not resolvable, otherwise this test won't be valid.
88+
Assert.Throws<ComponentNotRegisteredException>(() => mock.Resolve<string>());
89+
90+
var obj = mock.Resolve<WithStringProperty>();
91+
92+
Assert.IsNotNull(obj.Test);
93+
}
94+
7795
[Test]
7896
public void InjectPropertiesInterfaceRecursive()
7997
{
@@ -146,6 +164,11 @@ public class WithProperties
146164
public ITestInterface1 Service { get; set; }
147165
}
148166

167+
public class WithStringProperty
168+
{
169+
public virtual string Test { get; }
170+
}
171+
149172
public class Class1
150173
{
151174
}

AutofacContrib.NSubstitute/MockHandlers/AutoPropertyInjectorMockHandler.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,14 @@ public RouteAction Handle(ICall call)
3737
return RouteAction.Continue();
3838
}
3939

40-
return RouteAction.Return(_context.Resolve(call.GetReturnType()));
40+
var service = _context.ResolveOptional(call.GetReturnType());
41+
42+
if (service is null)
43+
{
44+
return RouteAction.Continue();
45+
}
46+
47+
return RouteAction.Return(service);
4148
}
4249
}
4350
}

0 commit comments

Comments
 (0)