2222namespace Ninject . MockingKernel . Moq
2323{
2424 using System ;
25+ using System . Linq ;
2526 using System . Reflection ;
2627
2728 using global ::Moq ;
@@ -45,6 +46,11 @@ public class MoqMockProvider : NinjectComponent, IProvider, IMockProviderCallbac
4546 /// </summary>
4647 private readonly MethodInfo createMethod ;
4748
49+ /// <summary>
50+ /// The method info used to add additional interface to mock.
51+ /// </summary>
52+ private readonly MethodInfo addAdditionalInterfaceMethod ;
53+
4854 /// <summary>
4955 /// Initializes a new instance of the <see cref="MoqMockProvider"/> class.
5056 /// </summary>
@@ -53,6 +59,7 @@ public MoqMockProvider(IMockRepositoryProvider mockRepositoryProvider)
5359 {
5460 this . mockRepository = mockRepositoryProvider . Instance ;
5561 this . createMethod = mockRepositoryProvider . CreateMethod ;
62+ this . addAdditionalInterfaceMethod = mockRepositoryProvider . AddAdditionalInterfaceMethod ;
5663 }
5764#endif
5865
@@ -87,6 +94,12 @@ public object Create(IContext context)
8794 {
8895 var methodInfo = this . createMethod . MakeGenericMethod ( context . Request . Service ) ;
8996 var mock = ( Mock ) methodInfo . Invoke ( this . mockRepository , new object [ 0 ] ) ;
97+ var additionalInterfaces = context . Parameters . OfType < AdditionalInterfaceParameter > ( ) . Select ( ai => ( Type ) ai . GetValue ( context , null ) ) ;
98+ foreach ( var additionalInterface in additionalInterfaces )
99+ {
100+ this . addAdditionalInterfaceMethod . MakeGenericMethod ( additionalInterface ) . Invoke ( mock , null ) ;
101+ }
102+
90103 return mock . Object ;
91104 }
92105
@@ -104,6 +117,12 @@ public object Create(IContext context)
104117 var mockType = typeof ( Mock < > ) . MakeGenericType ( context . Request . Service ) ;
105118 var constructorInfo = mockType . GetConstructor ( new [ ] { typeof ( MockBehavior ) } ) ;
106119 var mock = ( Mock ) constructorInfo . Invoke ( new object [ ] { Settings . GetMockBehavior ( ) } ) ;
120+ var additionalInterfaces = context . Parameters . OfType < AdditionalInterfaceParameter > ( ) . Select ( ai => ( Type ) ai . GetValue ( context , null ) ) ;
121+ foreach ( var additionalInterface in additionalInterfaces )
122+ {
123+ typeof ( Mock ) . GetMethod ( "As" ) . MakeGenericMethod ( additionalInterface ) . Invoke ( mock , null ) ;
124+ }
125+
107126 return mock . Object ;
108127 }
109128#endif
0 commit comments