Skip to content

Commit 0379436

Browse files
authored
Merge pull request #60 from autofac/feature/issue-48-delegate-mock
Support mocking delegate types (#48)
2 parents 7e2d9f3 + 5623078 commit 0379436

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

src/Autofac.Extras.Moq/AutoMock.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -202,8 +202,12 @@ public void Dispose()
202202
public Mock<T> Mock<T>(params Parameter[] parameters)
203203
where T : class
204204
{
205-
var obj = (IMocked<T>)Create<T>(true, parameters);
206-
return obj.Mock;
205+
// Mock.Get retrieves the Mock<T> from Moq's internal registry rather
206+
// than casting the resolved object to IMocked<T>. This is important for
207+
// delegate mocks (issue #48): the Object of a delegate mock is the
208+
// delegate itself and does not implement IMocked<T>, so a direct cast
209+
// would throw an InvalidCastException.
210+
return global::Moq.Mock.Get(Create<T>(true, parameters));
207211
}
208212

209213
/// <summary>

test/Autofac.Extras.Moq.Test/AutoMockFixture.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,20 @@ public void CreateClassWithParameter()
345345
}
346346
}
347347

348+
[Fact]
349+
public void MockOfDelegateTypeSucceeds()
350+
{
351+
// Issue #48 - mocking a delegate type used to throw InvalidCastException
352+
// because the delegate Object does not implement IMocked<T>.
353+
using (var mock = AutoMock.GetLoose())
354+
{
355+
var delegateMock = mock.Mock<TestDelegate>();
356+
delegateMock.Setup(x => x(It.IsAny<int>())).Returns(20);
357+
358+
Assert.Equal(20, delegateMock.Object.Invoke(5));
359+
}
360+
}
361+
348362
[Fact]
349363
public void MockedClassWithConstructorThrows()
350364
{
@@ -428,6 +442,8 @@ public ClassWithParameters(int param1, TimeSpan param2)
428442
}
429443
}
430444

445+
public delegate int TestDelegate(int x);
446+
431447
internal class ConsumesDisposable
432448
{
433449
private readonly ITestDisposable _disposable;

0 commit comments

Comments
 (0)