File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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>
Original file line number Diff line number Diff 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 ;
You can’t perform that action at this time.
0 commit comments