1
+ using Autofac ;
2
+ using NSubstitute . Core ;
3
+ using System ;
4
+ using System . Collections . Generic ;
5
+
6
+ namespace AutofacContrib . NSubstitute . MockHandlers
7
+ {
8
+ /// <summary>
9
+ /// An implementation of a <see cref="MockHandler"/> that will skip creation of mocks of type <typeparamref name="T"/>.
10
+ /// </summary>
11
+ public class SkipTypeMockHandler : MockHandler
12
+ {
13
+ private readonly IEnumerable < Type > _types ;
14
+
15
+ /// <summary>
16
+ /// Create a <see cref="MockHandler"/> that skips <typeparamref name="T"/>.
17
+ /// </summary>
18
+ /// <returns>A mock handler to skip supplied type.</returns>
19
+ public static MockHandler Create < T > ( ) => Create ( typeof ( T ) ) ;
20
+
21
+ /// <summary>
22
+ /// Create a <see cref="MockHandler"/> that skips all types contained in <paramref name="types"/>.
23
+ /// </summary>
24
+ /// <param name="types">List of types to return.</param>
25
+ /// <returns>A mock handler to skip supplied types.</returns>
26
+ public static MockHandler Create ( params Type [ ] types ) => new SkipTypeMockHandler ( types ) ;
27
+
28
+ /// <summary>
29
+ /// Create a <see cref="MockHandler"/> that skips all types contained in <paramref name="types"/>.
30
+ /// </summary>
31
+ /// <param name="types">List of types to return.</param>
32
+ /// <returns>A mock handler to skip supplied types.</returns>
33
+ public static MockHandler Create ( IEnumerable < Type > types ) => new SkipTypeMockHandler ( types ) ;
34
+
35
+ private SkipTypeMockHandler ( IEnumerable < Type > types )
36
+ {
37
+ _types = types ;
38
+ }
39
+
40
+ protected internal sealed override void OnMockCreated ( object instance , Type type , IComponentContext context , ISubstitutionContext substitutionContext )
41
+ => base . OnMockCreated ( instance , type , context , substitutionContext ) ;
42
+
43
+ protected internal override void OnMockCreating ( MockCreatingContext context )
44
+ {
45
+ foreach ( var type in _types )
46
+ {
47
+ if ( type == context . Type )
48
+ {
49
+ context . DoNotCreate ( ) ;
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
0 commit comments