-
-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathAutoMocker.cs
More file actions
1244 lines (1108 loc) · 52 KB
/
AutoMocker.cs
File metadata and controls
1244 lines (1108 loc) · 52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Text;
using Moq.AutoMock.Extensions;
using Moq.AutoMock.Resolvers;
using Moq.Language;
using Moq.Language.Flow;
namespace Moq.AutoMock;
/// <summary>
/// An auto-mocking IoC container that generates mock objects using Moq.
/// </summary>
public partial class AutoMocker : IServiceProvider
{
/// <summary>
/// Initializes an instance of AutoMockers.
/// </summary>
public AutoMocker()
: this(MockBehavior.Default)
{
}
/// <summary>
/// Initializes an instance of AutoMockers.
/// </summary>
/// <param name="mockBehavior">The behavior to use for created mocks.</param>
public AutoMocker(MockBehavior mockBehavior)
: this(mockBehavior, DefaultValue.Empty)
{
}
/// <summary>
/// Initializes an instance of AutoMockers.
/// </summary>
/// <param name="mockBehavior">The behavior to use for created mocks.</param>
/// <param name="defaultValue">The default value to use for created mocks.</param>
public AutoMocker(MockBehavior mockBehavior, DefaultValue defaultValue)
: this(mockBehavior, defaultValue, callBase: false)
{
}
/// <summary>
/// Initializes an instance of AutoMockers.
/// </summary>
/// <param name="mockBehavior">The behavior to use for created mocks.</param>
/// <param name="defaultValue">The default value to use for created mocks.</param>
/// <param name="callBase">Whether to call the base virtual implementation for created mocks.</param>
public AutoMocker(MockBehavior mockBehavior, DefaultValue defaultValue, bool callBase)
: this(mockBehavior, defaultValue, null, callBase)
{ }
/// <summary>
/// Initializes an instance of AutoMockers.
/// </summary>
/// <param name="mockBehavior">The behavior to use for created mocks.</param>
/// <param name="defaultValue">The default value to use for created mocks.</param>
/// <param name="defaultValueProvider">The instance that will be used to produce default return values for unexpected invocations.</param>
/// <param name="callBase">Whether to call the base virtual implementation for created mocks.</param>
public AutoMocker(MockBehavior mockBehavior, DefaultValue defaultValue, DefaultValueProvider? defaultValueProvider, bool callBase)
{
MockBehavior = mockBehavior;
DefaultValue = defaultValue;
DefaultValueProvider = defaultValueProvider;
CallBase = callBase;
Resolvers =
[
new CacheResolver(),
new CallbackResolver(),
new SelfResolver(),
new ArrayResolver(),
new AutoMockerDisposableResolver(),
new EnumerableResolver(),
new LazyResolver(),
new FuncResolver(),
new CancellationTokenResolver(),
new HttpClientResolver(),
new MockResolver(mockBehavior, defaultValue, defaultValueProvider, callBase)
];
}
/// <summary>
/// Behavior of created mocks, according to the value set in the constructor.
/// </summary>
public MockBehavior MockBehavior { get; }
/// <summary>
/// Specifies the behavior to use when returning default values for
/// unexpected invocations on loose mocks created by this instance.
/// </summary>
public DefaultValue DefaultValue { get; }
/// <summary>
/// Gets the <see cref="Moq.DefaultValueProvider"/> instance that will be used
/// to produce default return values for unexpected invocations.
/// </summary>
public DefaultValueProvider? DefaultValueProvider { get; }
/// <summary>
/// Whether the base member virtual implementation will be called
/// for created mocks if no setup is matched. Defaults to <c>false</c>.
/// </summary>
public bool CallBase { get; }
/// <summary>
/// A collection of resolves determining how a given dependency will be resolved.
/// </summary>
public IList<IMockResolver> Resolvers { get; }
/// <summary>
/// A collection of objects stored in this AutoMocker instance.
/// The keys are the types used when resolving services.
/// </summary>
public IReadOnlyDictionary<Type, object?> ResolvedObjects
//NB: NonBlocking.ConcurrentDictionary GetEnumerator method returns a snapshot enumerator which is thread-safe
=> TypeMap?.ToDictionary(kvp => kvp.Key, kvp =>
{
return kvp.Value switch
{
MockInstance mockInstance => mockInstance.Mock,
_ => kvp.Value.Value
};
}) ?? [];
private NonBlocking.ConcurrentDictionary<Type, IInstance>? TypeMap
=> Resolvers.OfType<CacheResolver>().FirstOrDefault()?.TypeMap;
private bool TryResolve(Type serviceType,
ObjectGraphContext resolutionContext,
[NotNullWhen(true)] out IInstance? instance,
out bool noCache)
{
if (resolutionContext.VisitedTypes.Contains(serviceType))
{
//Rejected due to circular dependency
instance = null;
noCache = false;
return false;
}
resolutionContext.VisitedTypes.Add(serviceType);
var context = new MockResolutionContext(this, serviceType, resolutionContext);
List<IMockResolver> resolvers = [.. Resolvers];
for (int i = 0; i < resolvers.Count && !context.ValueProvided; i++)
{
try
{
resolvers[i].Resolve(context);
}
catch (Exception ex)
{
resolutionContext.AddDiagnosticMessage($"Resolver: {resolvers[i].GetType().FullName} threw an exception while attempting to resolve service of type {serviceType.AssemblyQualifiedName} {ex}");
}
}
if (!context.ValueProvided)
{
instance = null;
noCache = false;
return false;
}
instance = context.Value switch
{
Mock mock => new MockInstance(mock),
IInstance i => i,
_ => new RealInstance(context.Value),
};
noCache = context.NoCache;
return true;
}
#region Create Instance
/// <summary>
/// Constructs an instance from known services. Any dependencies (constructor arguments)
/// are fulfilled by searching the container or, if not found, automatically generating
/// mocks.
/// </summary>
/// <typeparam name="T">A concrete type</typeparam>
/// <returns>An instance of T with all constructor arguments derived from services
/// setup in the container.</returns>
public T CreateInstance<T>() where T : class
=> CreateInstance<T>(false);
/// <summary>
/// Constructs an instance from known services. Any dependencies (constructor arguments)
/// are fulfilled by searching the container or, if not found, automatically generating
/// mocks.
/// </summary>
/// <typeparam name="T">A concrete type</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <returns>An instance of T with all constructor arguments derived from services
/// setup in the container.</returns>
public T CreateInstance<T>(bool enablePrivate) where T : class
=> (T)CreateInstance(typeof(T), enablePrivate);
/// <summary>
/// Constructs an instance from known services. Any dependencies (constructor arguments)
/// are fulfilled by searching the container or, if not found, automatically generating
/// mocks.
/// </summary>
/// <param name="type">A concrete type</param>
/// <returns>An instance of type with all constructor arguments derived from services
/// setup in the container.</returns>
public object CreateInstance(Type type) => CreateInstance(type, false);
/// <summary>
/// Constructs an instance from known services. Any dependencies (constructor arguments)
/// are fulfilled by searching the container or, if not found, automatically generating
/// mocks.
/// </summary>
/// <param name="type">A concrete type</param>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <returns>An instance of type with all constructor arguments derived from services
/// setup in the container.</returns>
public object CreateInstance(Type type, bool enablePrivate)
{
if (type is null) throw new ArgumentNullException(nameof(type));
var context = new ObjectGraphContext(enablePrivate);
return CreateInstanceInternal(type, context);
}
internal object CreateInstanceInternal(Type type, ObjectGraphContext context)
{
if (!TryGetConstructorInvocation(type, context, out ConstructorInfo? ctor, out IInstance[]? arguments))
{
throw new ObjectCreationException(
$"Did not find a best constructor for `{type}`. If any type in the hierarchy has a non-public constructor, set the 'enablePrivate' parameter to true for this {nameof(AutoMocker)} method.",
context.DiagnosticMessages);
}
try
{
object?[] parameters = [.. arguments.Select(x => x.Value)];
return ctor.Invoke(parameters);
}
catch (TargetInvocationException e)
{
ExceptionDispatchInfo.Capture(e.InnerException ?? e).Throw();
throw; //Not really reachable either way, but I like this better than return default(T)
}
}
#endregion Create Instance
#region CreateSelfMock
/// <summary>
/// Constructs a self-mock from the services available in the container. A self-mock is
/// a concrete object that has virtual and abstract members mocked. The purpose is so that
/// you can test the majority of a class but mock out a resource. This is great for testing
/// abstract classes, or avoiding breaking cohesion even further with a non-abstract class.
/// </summary>
/// <typeparam name="T">The instance that you want to build</typeparam>
/// <returns>An instance with virtual and abstract members mocked</returns>
public T CreateSelfMock<T>() where T : class
=> CreateSelfMock<T>(false);
/// <summary>
/// Constructs a self-mock from the services available in the container. A self-mock is
/// a concrete object that has virtual and abstract members mocked. The purpose is so that
/// you can test the majority of a class but mock out a resource. This is great for testing
/// abstract classes, or avoiding breaking cohesion even further with a non-abstract class.
/// </summary>
/// <typeparam name="T">The instance that you want to build</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <returns>An instance with virtual and abstract members mocked</returns>
public T CreateSelfMock<T>(bool enablePrivate) where T : class
=> CreateSelfMock<T>(enablePrivate, MockBehavior, DefaultValue, null, CallBase);
/// <summary>
/// Constructs a self-mock from the services available in the container. A self-mock is
/// a concrete object that has virtual and abstract members mocked. The purpose is so that
/// you can test the majority of a class but mock out a resource. This is great for testing
/// abstract classes, or avoiding breaking cohesion even further with a non-abstract class.
/// </summary>
/// <typeparam name="T">The instance that you want to build</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <param name="mockBehavior">Sets the Behavior property on the created Mock.</param>
/// <param name="defaultValue">Sets the DefaultValue property on the created Mock.</param>
/// <param name="defaultValueProvider">The instance that will be used to produce default return values for unexpected invocations.</param>
/// <param name="callBase">Sets the CallBase property on the created Mock.</param>
/// <returns>An instance with virtual and abstract members mocked</returns>
public T CreateSelfMock<T>(
bool enablePrivate = false,
MockBehavior? mockBehavior = null,
DefaultValue? defaultValue = null,
DefaultValueProvider? defaultValueProvider = null,
bool? callBase = null)
where T : class
{
return BuildSelfMock<T>(enablePrivate, mockBehavior ?? MockBehavior, defaultValue ?? DefaultValue, defaultValueProvider ?? DefaultValueProvider, callBase ?? CallBase).Object;
}
/// <summary>
/// This constructs a self mock similar to <see cref="CreateSelfMock{T}(bool, MockBehavior?, DefaultValue?, DefaultValueProvider?, bool?)" />.
/// The created mock instance is automatically registered using both its implementation and service type.
/// </summary>
/// <typeparam name="TService">The service type</typeparam>
/// <typeparam name="TImplementation">The implementation type</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <param name="mockBehavior">Sets the Behavior property on the created Mock.</param>
/// <param name="defaultValue">Sets the DefaultValue property on the created Mock.</param>
/// <param name="defaultValueProvider">The instance that will be used to produce default return values for unexpected invocations.</param>
/// <param name="callBase">Sets the CallBase property on the created Mock.</param>
/// <returns>A mock of the service</returns>
public Mock<TService> WithSelfMock<TService, TImplementation>(
bool enablePrivate = false,
MockBehavior? mockBehavior = null,
DefaultValue? defaultValue = null,
DefaultValueProvider? defaultValueProvider = null,
bool? callBase = null)
where TImplementation : class, TService
where TService : class
{
Mock<TImplementation> selfMock = BuildSelfMock<TImplementation>(
enablePrivate,
mockBehavior ?? MockBehavior,
defaultValue ?? DefaultValue,
defaultValueProvider ?? DefaultValueProvider,
callBase ?? CallBase);
Mock<TService> serviceMock = selfMock.As<TService>();
WithTypeMap(typeMap =>
{
typeMap[typeof(TImplementation)] = new MockInstance(selfMock);
typeMap[typeof(TService)] = new MockInstance(serviceMock);
});
return serviceMock;
}
/// <summary>
/// This constructs a self mock similar to <see cref="CreateSelfMock{T}(bool, MockBehavior?, DefaultValue?, DefaultValueProvider?, bool?)" />.
/// The created mock instance is automatically registered using both its implementation and service type.
/// </summary>
/// <typeparam name="T">The service type</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <param name="mockBehavior">Sets the Behavior property on the created Mock.</param>
/// <param name="defaultValue">Sets the DefaultValue property on the created Mock.</param>
/// <param name="defaultValueProvider">The instance that will be used to produce default return values for unexpected invocations.</param>
/// <param name="callBase">Sets the CallBase property on the created Mock.</param>
/// <returns>An instance with virtual and abstract members mocked</returns>
public T WithSelfMock<T>(
bool enablePrivate = false,
MockBehavior? mockBehavior = null,
DefaultValue? defaultValue = null,
DefaultValueProvider? defaultValueProvider = null,
bool? callBase = null)
where T : class
{
Mock<T> selfMock = BuildSelfMock<T>(enablePrivate, mockBehavior ?? MockBehavior, defaultValue ?? DefaultValue, defaultValueProvider ?? DefaultValueProvider, callBase ?? CallBase);
WithTypeMap(typeMap =>
{
typeMap[typeof(T)] = new MockInstance(selfMock);
});
return selfMock.Object;
}
/// <summary>
/// This constructs a self mock similar to <see cref="CreateSelfMock{T}(bool, MockBehavior?, DefaultValue?, DefaultValueProvider?, bool?)" />.
/// The created mock instance is automatically registered using both its implementation and service type.
/// </summary>
/// <param name="serviceType">The service type.</param>
/// <param name="implementationType">The implementation type of the service.</param>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <param name="mockBehavior">Sets the Behavior property on the created Mock.</param>
/// <param name="defaultValue">Sets the DefaultValue property on the created Mock.</param>
/// <param name="defaultValueProvider">The instance that will be used to produce default return values for unexpected invocations.</param>
/// <param name="callBase">Sets the CallBase property on the created Mock.</param>
/// <returns>An instance with virtual and abstract members mocked</returns>
public object WithSelfMock(
Type serviceType,
Type implementationType,
bool enablePrivate = false,
MockBehavior? mockBehavior = null,
DefaultValue? defaultValue = null,
DefaultValueProvider? defaultValueProvider = null,
bool? callBase = null)
{
Mock selfMock = BuildSelfMock(
implementationType,
enablePrivate,
mockBehavior ?? MockBehavior,
defaultValue ?? DefaultValue,
defaultValueProvider ?? DefaultValueProvider,
callBase ?? CallBase);
WithTypeMap(typeMap =>
{
typeMap[implementationType] = new MockInstance(selfMock);
typeMap[serviceType] = new MockInstance(selfMock.As(serviceType));
});
return selfMock.Object;
}
/// <summary>
/// This constructs a self mock similar to <see cref="CreateSelfMock{T}(bool, MockBehavior?, DefaultValue?, DefaultValueProvider?, bool?)" />.
/// The created mock instance is automatically registered using both its implementation and service type.
/// </summary>
/// <param name="implementationType">The implementation type of the service.</param>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <param name="mockBehavior">Sets the Behavior property on the created Mock.</param>
/// <param name="defaultValue">Sets the DefaultValue property on the created Mock.</param>
/// <param name="defaultValueProvider">The instance that will be used to produce default return values for unexpected invocations.</param>
/// <param name="callBase">Sets the CallBase property on the created Mock.</param>
/// <returns>An instance with virtual and abstract members mocked</returns>
public object WithSelfMock(
Type implementationType,
bool enablePrivate = false,
MockBehavior? mockBehavior = null,
DefaultValue? defaultValue = null,
DefaultValueProvider? defaultValueProvider = null,
bool? callBase = null)
{
Mock selfMock = BuildSelfMock(
implementationType,
enablePrivate,
mockBehavior ?? MockBehavior,
defaultValue ?? DefaultValue,
defaultValueProvider ?? DefaultValueProvider,
callBase ?? CallBase);
WithTypeMap(typeMap =>
{
typeMap[implementationType] = new MockInstance(selfMock);
});
return selfMock.Object;
}
private Mock<T> BuildSelfMock<T>(bool enablePrivate, MockBehavior mockBehavior, DefaultValue defaultValue, DefaultValueProvider? defaultValueProvider, bool callBase)
where T : class
{
var context = new ObjectGraphContext(enablePrivate);
return CreateMock(typeof(T), mockBehavior, defaultValue, defaultValueProvider, callBase, context) is Mock<T> mock
? mock
: throw new InvalidOperationException($"Failed to create self mock of type {typeof(T).FullName}");
}
private Mock BuildSelfMock(Type serviceType, bool enablePrivate, MockBehavior mockBehavior, DefaultValue defaultValue, DefaultValueProvider? defaultValueProvider, bool callBase)
{
var context = new ObjectGraphContext(enablePrivate);
return CreateMock(serviceType, mockBehavior, defaultValue, defaultValueProvider, callBase, context) is Mock mock
? mock
: throw new InvalidOperationException($"Failed to create self mock of type {serviceType.FullName}");
}
#endregion CreateSelfMock
#region Use
/// <summary>
/// Adds an instance to the container.
/// </summary>
/// <typeparam name="TService">The type that the instance will be registered as</typeparam>
/// <param name="service"></param>
/// <returns>Itself</returns>
public AutoMocker Use<TService>(TService? service)
=> Use(typeof(TService), service);
/// <summary>
/// Adds an instance to the container.
/// </summary>
/// <param name="type">The type of service to use</param>
/// <param name="service">The service to use</param>
/// <returns>Itself</returns>
public AutoMocker Use(Type type, object? service)
{
if (type is null) throw new ArgumentNullException(nameof(type));
if (service != null && !type.IsInstanceOfType(service))
{
throw new ArgumentException($"{nameof(service)} is not of type {type}", nameof(service));
}
WithTypeMap(typeMap =>
{
if (typeMap.TryGetValue(type, out IInstance existingInstance) &&
existingInstance is RealInstance realInstance &&
Equals(realInstance.Value, service))
{
throw new InvalidOperationException($"The service instance has already been added. You can safely remove this call to {nameof(AutoMocker)}.{nameof(Use)}");
}
typeMap[type] = new RealInstance(service);
});
return this;
}
/// <summary>
/// Adds an instance to the container.
/// </summary>
/// <typeparam name="TService">The type that the instance will be registered as</typeparam>
/// <param name="mockedService">The mocked service</param>
/// <returns>Itself</returns>
public AutoMocker Use<TService>(Mock<TService> mockedService)
where TService : class
{
WithTypeMap(typeMap =>
{
Type serviceType = typeof(TService);
if (typeMap.TryGetValue(serviceType, out IInstance existingInstance) &&
existingInstance is MockInstance mockInstance &&
Equals(mockInstance.Mock.Object, mockedService.Object))
{
throw new InvalidOperationException("The service has already been added.");
}
typeMap[serviceType] = new MockInstance(mockedService ?? throw new ArgumentNullException(nameof(mockedService)));
});
return this;
}
/// <summary>
/// Adds a mock object to the container that implements TService.
/// </summary>
/// <typeparam name="TService">The type that the instance will be registered as</typeparam>
/// <param name="setup">A shortcut for Mock.Of's syntax</param>
/// <returns>Itself</returns>
/// <exception cref="ArgumentNullException">When the setup expression is null.</exception>
public AutoMocker Use<TService>(Expression<Func<TService, bool>> setup)
where TService : class
{
if (setup is null) throw new ArgumentNullException(nameof(setup));
return Use(Mock.Get(Mock.Of(setup)));
}
/// <summary>
/// Adds a callback delegate to the container.
/// This delegate will be invoked when the service type is first requested.
/// The resulting value will be cached.
/// </summary>
/// <typeparam name="TService">The type that the instance will be registered as</typeparam>
/// <param name="factory">Teh factory callback.</param>
/// <returns>Itself</returns>
/// <exception cref="ArgumentNullException">When the factory is null.</exception>
public AutoMocker Use<TService>(Func<AutoMocker, TService> factory)
where TService : class
{
if (factory is null) throw new ArgumentNullException(nameof(factory));
CallbackResolver resolver = Resolvers.OfType<CallbackResolver>().FirstOrDefault()
?? throw new InvalidOperationException($"The {nameof(CallbackResolver)} must be a registered resolver.");
resolver.AddCallback(factory);
return this;
}
/// <summary>
/// Adds a callback delegate to the container.
/// This delegate will be invoked when the service type is first requested.
/// The resulting value will be cached.
/// </summary>
/// <typeparam name="TService">The type that the instance will be registered as</typeparam>
/// <param name="factory">Teh factory callback.</param>
/// <returns>Itself</returns>
/// <exception cref="ArgumentNullException">When the factory is null.</exception>
public AutoMocker Use<TService>(Func<TService> factory)
where TService : class
{
return Use(_ => factory());
}
/// <summary>
/// Adds a callback delegate to the container.
/// This delegate will be invoked when the service type is first requested.
/// The resulting value will be cached.
/// </summary>
/// <typeparam name="TService">The type that the instance will be registered as</typeparam>
/// <typeparam name="TImplementation">The service implementation type</typeparam>
/// <returns>Itself</returns>
/// <exception cref="ArgumentNullException">When the factory is null.</exception>
public AutoMocker Use<TService, TImplementation>()
where TService : class
where TImplementation: class, TService
{
return Use(mocker => mocker.Get<TImplementation>());
}
/// <summary>
/// Creates an instance of <typeparamref name="TImplementation"/> and registers it as for service type <typeparamref name="TService"/>.
/// This is a convenience method for Use<<typeparamref name="TService"/>>(CreateInstance<<typeparamref name="TImplementation"/>>())
/// </summary>
/// <typeparam name="TService">The service type</typeparam>
/// <typeparam name="TImplementation">The service implementation type</typeparam>
/// <returns>The created instance</returns>
public TImplementation With<TService, TImplementation>()
where TImplementation : class, TService
{
TImplementation instance = CreateInstance<TImplementation>();
Use<TService>(instance);
return instance;
}
/// <summary>
/// Creates an instance of <typeparamref name="TImplementation"/> and registers it as for service type <typeparamref name="TImplementation"/>.
/// This is a convenience method for Use<<typeparamref name="TImplementation"/>>(CreateInstance<<typeparamref name="TImplementation"/>>())
/// </summary>
/// <typeparam name="TImplementation">The service implementation type</typeparam>
/// <returns>The created instance</returns>
public TImplementation With<TImplementation>()
where TImplementation : class
{
TImplementation instance = CreateInstance<TImplementation>();
Use(instance);
return instance;
}
/// <summary>
/// Creates an instance of <paramref name="implementationType"/> and registers it for service type <paramref name="serviceType"/>.
/// This is a convenience method for Use(<paramref name="serviceType"/>, CreateInstance(<paramref name="implementationType"/>))
/// </summary>
/// <returns>The created instance</returns>
public object With(Type serviceType, Type implementationType)
{
object instance = CreateInstance(implementationType);
Use(serviceType, instance);
return instance;
}
/// <summary>
/// Creates an instance of <paramref name="implementationType"/> and registers it for service type <paramref name="implementationType"/>.
/// This is a convenience method for Use(<paramref name="implementationType"/>, CreateInstance(<paramref name="implementationType"/>))
/// </summary>
/// <returns>The created instance</returns>
public object With(Type implementationType)
{
object instance = CreateInstance(implementationType);
Use(implementationType, instance);
return instance;
}
#endregion Use
#region Get
/// <summary>
/// Searches and retrieves an object from the container that matches TService. This can be
/// a service setup explicitly via `.Use()` or implicitly with `.CreateInstance()`.
/// </summary>
/// <typeparam name="TService">The class or interface to search on</typeparam>
/// <returns>The object that implements TService</returns>
public TService Get<TService>()
{
if (Get(typeof(TService)) is TService service)
return service;
return default!;
}
/// <summary>
/// Searches and retrieves an object from the container that matches TService. This can be
/// a service setup explicitly via `.Use()` or implicitly with `.CreateInstance()`.
/// </summary>
/// <typeparam name="TService">The class or interface to search on</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <returns>The object that implements TService</returns>
public TService Get<TService>(bool enablePrivate)
{
if (Get(typeof(TService), enablePrivate) is TService service)
return service;
return default!;
}
/// <summary>
/// Searches and retrieves an object from the container that matches the serviceType. This can be
/// a service setup explicitly via `.Use()` or implicitly with `.CreateInstance()`.
/// </summary>
/// <param name="serviceType">The type of service to retrieve</param>
/// <returns></returns>
public object Get(Type serviceType)
{
return Get(serviceType, enablePrivate: false);
}
/// <summary>
/// Searches and retrieves an object from the container that matches the serviceType. This can be
/// a service setup explicitly via `.Use()` or implicitly with `.CreateInstance()`.
/// </summary>
/// <param name="serviceType">The type of service to retrieve</param>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <returns></returns>
public object Get(Type serviceType, bool enablePrivate)
{
return Get(serviceType, new ObjectGraphContext(enablePrivate));
}
private object Get(Type serviceType, ObjectGraphContext context)
{
if (TryGet(serviceType, context, out IInstance? service, out bool noCache))
{
if (!noCache && TypeMap is { } typeMap && !typeMap.ContainsKey(serviceType))
{
typeMap[serviceType] = service;
}
return service.Value!; //Should generally not be null, unless the caller has forced a null in with Use
}
throw new ArgumentException($"{serviceType} could not resolve to an object.", nameof(serviceType));
}
internal bool TryGet(
Type serviceType,
ObjectGraphContext context,
[NotNullWhen(true)] out IInstance? service,
out bool noCache)
{
if (serviceType is null) throw new ArgumentNullException(nameof(serviceType));
if (TryResolve(serviceType, context, out IInstance? instance, out noCache))
{
service = instance;
return true;
}
service = null;
return false;
}
/// <inheritdoc />
object? IServiceProvider.GetService(Type serviceType)
{
if (TryGet(serviceType, new ObjectGraphContext(false), out IInstance? service, out bool noCache))
{
if (!noCache && TypeMap is { } typeMap && !typeMap.ContainsKey(serviceType))
{
typeMap[serviceType] = service;
}
return service.Value;
}
return null;
}
#endregion Get
#region GetMock
/// <summary>
/// Searches and retrieves the mock that the container uses for TService.
/// </summary>
/// <typeparam name="TService">The class or interface to search on</typeparam>
/// <exception cref="ArgumentException">if the requested object wasn't a Mock</exception>
/// <returns>A mock of TService</returns>
public Mock<TService> GetMock<TService>() where TService : class
=> (Mock<TService>)GetMock(typeof(TService));
/// <summary>
/// Searches and retrieves the mock that the container uses for TService.
/// </summary>
/// <typeparam name="TService">The class or interface to search on</typeparam>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <exception cref="ArgumentException">if the requested object wasn't a Mock</exception>
/// <returns>A mock of TService</returns>
public Mock<TService> GetMock<TService>(bool enablePrivate) where TService : class
=> (Mock<TService>)GetMock(typeof(TService), enablePrivate);
/// <summary>
/// Searches and retrieves the mock that the container uses for serviceType.
/// </summary>
/// <param name="serviceType">The type of service to retrieve</param>
/// <returns>A mock of serviceType</returns>
public Mock GetMock(Type serviceType)
{
if (serviceType is null) throw new ArgumentNullException(nameof(serviceType));
return GetMock(serviceType, enablePrivate: false);
}
/// <summary>
/// Searches and retrieves the mock that the container uses for serviceType.
/// </summary>
/// <param name="serviceType">The type of service to retrieve</param>
/// <param name="enablePrivate">When true, non-public constructors will also be used to create mocks.</param>
/// <returns>A mock of serviceType</returns>
public Mock GetMock(Type serviceType, bool enablePrivate)
{
if (serviceType is null) throw new ArgumentNullException(nameof(serviceType));
return GetMockImplementation(serviceType, enablePrivate);
}
private Mock GetMockImplementation(Type serviceType, bool enablePrivate)
{
if (TryResolve(serviceType, new ObjectGraphContext(enablePrivate, isMockCreation:true), out IInstance? instance, out bool noCache) &&
instance.IsMock)
{
if (!noCache && TypeMap is { } typeMap && !typeMap.ContainsKey(serviceType))
{
typeMap[serviceType] = instance;
}
var mockInstance = (MockInstance)instance;
return mockInstance.Mock;
}
throw new ArgumentException($"Registered service `{Get(serviceType)?.GetType()}` was not a mock");
}
#endregion GetMock
#region Setup
/// <summary>
/// Shortcut for mock.Setup(...), creating the mock when necessary.
/// </summary>
public ISetup<TService> Setup<TService>(Expression<Action<TService>> setup)
where TService : class
{
return Setup<ISetup<TService>, TService>(m => m.Setup(setup));
}
/// <summary>
/// Shortcut for mock.Setup(...), creating the mock when necessary.
/// For specific return types. E.g. primitive, structs
/// that cannot be inferred
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <param name="setup"></param>
/// <returns></returns>
public ISetup<TService, TReturn> Setup<TService, TReturn>(Expression<Func<TService, TReturn>> setup)
where TService : class
{
return Setup<ISetup<TService, TReturn>, TService>(m => m.Setup(setup));
}
/// <summary>
/// Specifies a setup on the mocked type for a call to a void method.
/// All parameters are filled with <see cref ="It.IsAny" /> according to the parameter's type.
/// </summary>
/// <remarks>
/// This may only be used on methods that are not overloaded.
/// This will create the mock when necessary.
/// </remarks>
/// <typeparam name="TService">The service type</typeparam>
/// <param name="methodName">The name of the expected method invocation.</param>
/// <exception cref="ArgumentNullException">When the methodName is null.</exception>
/// <exception cref="MissingMethodException">Thrown when no method with methodName is found.</exception>
/// <exception cref="AmbiguousMatchException">Thrown when more that one method matches the passed method name.</exception>
/// <returns></returns>
public ISetup<TService> SetupWithAny<TService>(string methodName)
where TService : class
{
return Setup<ISetup<TService>, TService>(m => m.SetupWithAny(methodName));
}
/// <summary>
/// Specifies a setup on the mocked type for a call to a non-void (value-returning) method.
/// All parameters are filled with <see cref ="It.IsAny" /> according to the parameter's type.
/// </summary>
/// <remarks>
/// This may only be used on methods that are not overloaded.
/// This will create the mock when necessary.
/// </remarks>
/// <typeparam name="TService">The service type</typeparam>
/// <typeparam name="TReturn">The return type of the method</typeparam>
/// <param name="methodName">The name of the expected method invocation.</param>
/// <exception cref="ArgumentNullException">When the methodName is null.</exception>
/// <exception cref="MissingMethodException">Thrown when no method with methodName is found.</exception>
/// <exception cref="AmbiguousMatchException">Thrown when more that one method matches the passed method name.</exception>
/// <returns></returns>
public ISetup<TService, TReturn> SetupWithAny<TService, TReturn>(string methodName)
where TService : class
{
return Setup<ISetup<TService, TReturn>, TService>(m => m.SetupWithAny<TService, TReturn>(methodName));
}
private TReturn Setup<TReturn, TService>(Func<Mock<TService>, TReturn> returnValue)
where TService : class
{
var mock = (Mock<TService>)GetOrMakeMockFor(typeof(TService));
return returnValue(mock);
}
/// <summary>
/// Shortcut for mock.SetupAllProperties(), creating the mock when necessary
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <returns></returns>
public Mock<TService> SetupAllProperties<TService>() where TService : class
{
var mock = (Mock<TService>)GetOrMakeMockFor(typeof(TService));
mock.SetupAllProperties();
return mock;
}
/// <summary>
/// Shortcut for mock.SetupSequence(), creating the mock when necessary
/// </summary>
/// <typeparam name="TService"></typeparam>
/// <typeparam name="TReturn"></typeparam>
/// <returns></returns>
public ISetupSequentialResult<TReturn> SetupSequence<TService, TReturn>(Expression<Func<TService, TReturn>> setup)
where TService : class
{
if (setup is null) throw new ArgumentNullException(nameof(setup));
return Setup<ISetupSequentialResult<TReturn>, TService>(m => m.SetupSequence(setup));
}
#endregion
#region Combine
/// <summary>
/// Combines all given types so that they are mocked by the same
/// mock. Some IoC containers call this "Forwarding" one type to
/// other interfaces. In the end, this just means that all given
/// types will be implemented by the same instance.
/// </summary>
public void Combine(Type type, params Type[] forwardTo)
{
if (type is null) throw new ArgumentNullException(nameof(type));
if (!(TypeMap is { } typeMap)) throw new InvalidOperationException($"{nameof(CacheResolver)} was not found. Cannot combine types without resolver.");
Mock mock = forwardTo.Aggregate(GetOrMakeMockFor(type), As);
foreach (var serviceType in new[] { type }.Concat(forwardTo))
{
typeMap[serviceType] = new MockInstance(mock);
}
static Mock As(Mock mock, Type forInterface)
{
var method = mock.GetType().GetMethods().First(x => x.Name == nameof(Mock.As))
.MakeGenericMethod(forInterface);
return (Mock)method.Invoke(mock, [])!;
}
}
#endregion Combine
#region Verify
/// <summary>
/// This is a shortcut for calling `mock.VerifyAll()` on every mock that we have.
/// </summary>
public void VerifyAll(bool ignoreMissingSetups = false)
{
if (!(TypeMap is { } typeMap)) throw new InvalidOperationException($"{nameof(CacheResolver)} was not found. Cannot verify expectations without resolver.");
bool foundSetups = false;
foreach (var pair in typeMap)
{
if (pair.Value is MockInstance instance)
{
foundSetups |= instance.Mock.Setups.Any();
instance.Mock.VerifyAll();
}
}
if (!ignoreMissingSetups && !foundSetups)
{
throw new InvalidOperationException($"{nameof(VerifyAll)} was called, but there were no setups on any tracked mock instances to verify");
}
}
/// <summary>
/// This is a shortcut for calling `mock.Verify()` on every mock that we have.
/// </summary>
public void Verify()
{
if (!(TypeMap is { } typeMap)) throw new InvalidOperationException($"{nameof(CacheResolver)} was not found. Cannot verify expectations without resolver.");
foreach (var pair in typeMap)
{
if (pair.Value is MockInstance instance)
instance.Mock.Verify();
}
}
/// <summary>
/// Verify a mock in the container.
/// </summary>
/// <typeparam name="T">Type of the mock</typeparam>
/// <typeparam name="TResult">Return type of the full expression</typeparam>
/// <param name="expression"></param>
public void Verify<T, TResult>(Expression<Func<T, TResult>> expression)
where T : class
{
if (expression is null) throw new ArgumentNullException(nameof(expression));
var mock = GetMock<T>();
mock.Verify(expression);
}
/// <summary>
/// Verify a mock in the container.
/// </summary>
/// <typeparam name="T">Type of the mock</typeparam>
/// <typeparam name="TResult">Return type of the full expression</typeparam>
/// <param name="expression"></param>
/// <param name="times"></param>
public void Verify<T, TResult>(Expression<Func<T, TResult>> expression, Times times)
where T : class
{
if (expression is null) throw new ArgumentNullException(nameof(expression));
var mock = GetMock<T>();
mock.Verify(expression, times);
}