protected override void OnMocksRepositoryCreated(MocksRepository repo) { // MSTest runs every test in a different thread. We'd like to collect Thread objects often so that their handle is released. // At every N created repos (we assume that each test creates a single repo, so the number of repos created is close to // the number of threads created) do a garbage collection, but only if it hasn't been already done in this interval. createdRepoCount++; if (createdRepoCount % gcFrequency == 0) { var gen2Collections = GC.CollectionCount(GC.MaxGeneration); if (gen2Collections == lastGcCount) { if (synchronousGc) { GC.Collect(); } else { ThreadPool.QueueUserWorkItem(_ => GC.Collect()); } gen2Collections++; } lastGcCount = gen2Collections; } }
public static MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior) { var stackTrace = new StackTrace(); MethodBase callingMethodOutsideJustmock = null; foreach (var method in stackTrace.EnumerateFrames()) { if (contextMethod == method) return contextRepository; if (callingMethodOutsideJustmock == null && method.Module.Assembly != typeof(MocksRepository).Assembly) callingMethodOutsideJustmock = method; } if (callingMethodOutsideJustmock != null && unresolvedContextBehavior == UnresolvedContextBehavior.CreateNewContextualOrLocal) { // don't reset the old repository - because the mocks created from it may still be used, e.g. if the method // associated with ResolveRepository works as a factory for mocks which are then exercised elsewhere contextMethod = callingMethodOutsideJustmock; contextRepository = new MocksRepository(null, contextMethod); return contextRepository; } return null; }
public static MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior) { if (repository == null) { repository = new MocksRepository(null, null); } return repository; }
public static object Create(Type resultCollectionType, MocksRepository repo, IMockReplicator replicator, IEnumerable collection) { if (resultCollectionType == typeof(string)) return null; Type sourceType = collection.GetType(); if (resultCollectionType.IsAssignableFrom(sourceType)) return collection; var enumerableType = resultCollectionType.GetImplementationOfGenericInterface(typeof(IEnumerable<>)) ?? typeof(IEnumerable); if (!enumerableType.IsAssignableFrom(resultCollectionType)) throw new MockException("Return value is not an enumerable type."); var elementType = enumerableType.IsGenericType ? enumerableType.GetGenericArguments()[0] : typeof(object); var ilistType = typeof(IList<>).MakeGenericType(elementType); var iqueryableType = typeof(IQueryable<>).MakeGenericType(elementType); IEnumerable list; if (typeof(ICollection).IsAssignableFrom(sourceType)) { list = collection; } else { var listType = typeof(List<>).MakeGenericType(elementType); var castMethod = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(elementType); var castCollection = castMethod.Invoke(null, new[] { collection }); list = (IEnumerable)MockingUtil.CreateInstance(listType, castCollection); } var listBehavior = new DelegatedImplementationBehavior(list, new[] { ilistType, typeof(IList), }); var queryable = list.AsQueryable(); var queryableType = queryable.GetType(); var queryableBehavior = new DelegatedImplementationBehavior(queryable, new[] { queryableType.GetImplementationOfGenericInterface(typeof(IQueryable<>)) }); if (replicator != null) { var mock = replicator.CreateSimilarMock(repo, resultCollectionType, null, true, null); var mockMixin = MocksRepository.GetMockMixin(mock, null); mockMixin.FallbackBehaviors.Insert(0, queryableBehavior); mockMixin.FallbackBehaviors.Insert(0, listBehavior); return mock; } else { return repo.Create(resultCollectionType, null, Behavior.Loose, MockingUtil.EmptyTypes, null, null, null, new List<IBehavior> { listBehavior, queryableBehavior }); } }
public override void RetireRepository(object key, MocksRepository repo) { var dict = currentRepositories.GetAllThreadsValues().FirstOrDefault(repos => repos.ContainsValue(repo)); if (dict != null) { dict.Remove(key); repo.Retire(); } }
internal Invocation(object instance, MethodBase method, object[] args) { this.Instance = instance; this.Method = method; this.Args = args; this.MockMixin = method.IsExtensionMethod() && args.Length >= 1 ? MocksRepository.GetMockMixin(args[0], null) : MocksRepository.GetMockMixin(instance, method.DeclaringType); }
public object Create(Type type, MocksRepository repository, IMockMixin mockMixinImpl, MockCreationSettings settings, bool createTransparentProxy) { var baseType = type.IsGenericType ? type.GetGenericTypeDefinition() : type; RuntimeTypeHandle proxyTypeHandle; var key = new ProxySourceRegistry.ProxyKey( baseType.TypeHandle, GetAdditionalInterfaceHandles(type, settings.AdditionalMockedInterfaces)); if (!ProxySourceRegistry.ProxyTypes.TryGetValue(key, out proxyTypeHandle)) { ThrowNoProxyException(baseType, settings.AdditionalMockedInterfaces); } var interceptor = new DynamicProxyInterceptor(repository); var proxyType = Type.GetTypeFromHandle(proxyTypeHandle); if (proxyType.IsGenericTypeDefinition) proxyType = proxyType.MakeGenericType(type.GetGenericArguments()); var mockConstructorCall = settings.MockConstructorCall && proxyType.BaseType != typeof(object) && UninitializedObjectFactory.IsSupported; ConstructorInfo proxyCtor = null; if (!mockConstructorCall && settings.Args == null) { proxyCtor = proxyType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .First(ctor => ctor.IsPublic || ctor.IsFamily || ctor.IsFamilyOrAssembly); settings.Args = proxyCtor.GetParameters() .TakeWhile(p => p.ParameterType != typeof(IInterceptor)) .Select(p => (p.Attributes & ParameterAttributes.HasDefault) != 0 ? p.DefaultValue : p.ParameterType.GetDefaultValue()) .ToArray(); } var ctorArgs = (settings.Args ?? Enumerable.Empty<object>()) .Concat(new object[] { interceptor, mockMixinImpl }) .Concat(settings.Mixins).ToArray(); if (!mockConstructorCall) { if (proxyCtor != null) { return ProfilerInterceptor.GuardExternal(() => proxyCtor.Invoke(ctorArgs)); } else { return ProfilerInterceptor.GuardExternal(() => Activator.CreateInstance(proxyType, ctorArgs)); } } else { var result = UninitializedObjectFactory.Create(proxyType); proxyType.GetMethod(".init").Invoke(result, ctorArgs); return result; } }
public void Process(Invocation invocation) { var method = invocation.Method; if (method is ConstructorInfo && !method.IsStatic) { var mixin = MocksRepository.GetMockMixinFromInvocation(invocation); invocation.CallOriginal = mixin != null ? !mixin.IsInstanceConstructorMocked : true; invocation.UserProvidedImplementation = true; } }
public static void RetireRepository() { var stackTrace = new StackTrace(); if (stackTrace.EnumerateFrames().Contains(contextMethod)) { contextRepository.Retire(); contextMethod = null; contextRepository = null; } }
internal static void RegisterGlobalInterceptor(MethodBase method, MocksRepository repo) { lock (globalInterceptors) { List <MocksRepository> repos; if (!globalInterceptors.TryGetValue(method, out repos)) { globalInterceptors[method] = repos = new List <MocksRepository>(); } repos.Add(repo); } }
public static void RetireRepository() { var stackTrace = new StackTrace(); if (stackTrace.EnumerateFrames().Contains(contextMethod)) { contextRepository.Retire(); contextMethod = null; contextRepository = null; } }
internal static void UnregisterGlobalInterceptor(MethodBase method, MocksRepository repo) { lock (globalInterceptors) { var repos = globalInterceptors[method]; repos.Remove(repo); if (repos.Count == 0) { globalInterceptors.Remove(method); } } }
public void Process(Invocation invocation) { var mockMixin = MocksRepository.GetMockMixinFromInvocation(invocation); if (mockMixin == null) { mockMixin = invocation.Repository.CreateExternalMockMixin(null, invocation.Instance, Behavior.CallOriginal); mockMixin.IsInstanceConstructorMocked = true; } invocation.CallOriginal = !mockMixin.IsInstanceConstructorMocked; }
public static IMockMixin CreateExternalMockMixin(this MocksRepository repository, Type type, object mockObject, Behavior?behavior) { if (behavior == null) { behavior = DefaultBehavior; } var supplementaryBehaviors = new List <IBehavior>(); var fallbackBehaviors = new List <IBehavior>(); var mixins = new List <object>(); DissectBehavior(behavior.Value, mixins, supplementaryBehaviors, fallbackBehaviors, constructorArgs: null, mockConstructorCall: null); return(repository.CreateExternalMockMixin(type, mockObject, mixins, supplementaryBehaviors, fallbackBehaviors)); }
private MethodInfo GetGenericMethodInstance(Type targetType, Type returnType, string memberName, Type[] typeArguments, params object[] args) { var type = targetType; var mixin = MocksRepository.GetMockMixin(targetType, null); if (mixin != null) { type = mixin.DeclaringType; } var method = MockingUtil.GetGenericMethodInstanceByName(type, returnType, memberName, typeArguments, ref args); return(method); }
public static void InterceptStatics(this MocksRepository repository, Type type, Behavior?behavior, bool mockStaticConstructor) { if (behavior == null) { behavior = DefaultBehavior; } var supplementaryBehaviors = new List <IBehavior>(); var fallbackBehaviors = new List <IBehavior>(); var mixins = new List <object>(); DissectBehavior(behavior.Value, mixins, supplementaryBehaviors, fallbackBehaviors, constructorArgs: null, mockConstructorCall: null); repository.InterceptStatics(type, mixins, supplementaryBehaviors, fallbackBehaviors, mockStaticConstructor); }
public void Assert(object target, string memberName, Occurs occurs, params object[] args) { ProfilerInterceptor.GuardInternal(() => { var type = target.GetType(); var mixin = MocksRepository.GetMockMixin(target, null); if (mixin != null) { type = mixin.DeclaringType; } var method = GetMethodByName(type, typeof(void), memberName, ref args); MockingContext.CurrentRepository.AssertMethodInfo(target, method, args, occurs); }); }
public ProxyTypeInfo CreateClassProxyType(Type classToProxy, MocksRepository repository, MockCreationSettings settings, MockMixin mockMixinImpl) { var pgo = CreateProxyGenerationOptions(classToProxy, settings, mockMixinImpl); var typeInfo = new ProxyTypeInfo { ProxyType = generator.ProxyBuilder.CreateClassProxyType(classToProxy, Type.EmptyTypes, pgo) }; typeInfo.Mixins.Add(typeof(IInterceptor), new DynamicProxyInterceptor(repository)); foreach (var mixin in pgo.MixinData.MixinInterfaces) { typeInfo.Mixins.Add(mixin, pgo.MixinData.GetMixinInstance(mixin)); } return(typeInfo); }
public FuncExpectation <TReturn> Arrange <TReturn>(object target, string memberName, params object[] args) { return(ProfilerInterceptor.GuardInternal(() => { var type = target.GetType(); var mixin = MocksRepository.GetMockMixin(target, null); if (mixin != null) { type = mixin.DeclaringType; } var method = GetMethodByName(type, typeof(TReturn), memberName, ref args); return MockingContext.CurrentRepository.Arrange(target, method, args, () => new FuncExpectation <TReturn>()); })); }
/// <summary> /// Implementation detail. /// </summary> /// <param name="value"></param> protected void ProcessReturnsValue(TReturn value) { this.CheckConstructorArrangement(); this.ProcessDoInstead(new Func <TReturn>(() => value), false); if ((object)value != null) { var mock = MocksRepository.GetMockMixin(value, typeof(TReturn)); if (mock != null && this.Mock != null) { this.Mock.DependentMocks.Add(value); } } }
public int GetTimesCalled(object target, string memberName, params object[] args) { return(ProfilerInterceptor.GuardInternal(() => { var type = target.GetType(); var mixin = MocksRepository.GetMockMixin(target, null); if (mixin != null) { type = mixin.DeclaringType; } var method = GetMethodByName(type, typeof(void), memberName, ref args); return MockingContext.CurrentRepository.GetTimesCalledFromMethodInfo(target, method, args); })); }
public override MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior) { RepositoryOperationsBase entryOps = null; int repoIdx; var testMethod = FindTestMethod(out repoIdx, out entryOps); if (testMethod == null) return null; var entryKey = entryOps.GetKey(testMethod); MocksRepository repo = FindRepositoryInOps(entryOps, entryKey); if (repo != null) return repo; if (unresolvedContextBehavior == UnresolvedContextBehavior.DoNotCreateNew) return null; //Check if this is the same kind of method but from a derived class, thus building context. MocksRepository parentRepo = entryOps.FindRepositoryToInherit(testMethod); if (parentRepo == null) { for (var repoIdxParent = repoIdx + 1; parentRepo == null && repoIdxParent < this.repoOperations.Count; ++repoIdxParent) { var ops = this.repoOperations[repoIdxParent]; if (ops.IsLeaf) continue; var parentKey = ops.GetKey(testMethod); if (ops.IsUsedOnAllThreads) parentRepo = ops.FindRepositoryFromAnyThread(parentKey); else parentRepo = ops.FindRepository(parentKey) ?? ops.FindRepositoryToInherit(testMethod); } } MocksRepository entryRepo; try { entryRepo = new MocksRepository(parentRepo, testMethod); entryOps.AddRepository(entryKey, entryRepo); OnMocksRepositoryCreated(repo); } catch (TypeInitializationException e) { throw e.InnerException; } return entryRepo; }
private MocksRepository FindRepository(Dictionary <object, WeakReference> repos, object key) { WeakReference repo; MocksRepository ret = null; if (repos.TryGetValue(key, out repo)) { ret = (MocksRepository)repo.Target; if (ret == null) { Cleanup(repos); } } return(ret); }
public void Assert <TReturn>(object target, string memberName, params object[] args) { ProfilerInterceptor.GuardInternal(() => { var type = target.GetType(); var mixin = MocksRepository.GetMockMixin(target, null); if (mixin != null) { type = mixin.DeclaringType; } var message = MockingUtil.GetAssertionMessage(args); var method = MockingUtil.GetMethodByName(type, typeof(TReturn), memberName, ref args); MockingContext.CurrentRepository.AssertMethodInfo(message, target, method, args, null); }); }
public void Intercept(IInvocation invocation) { if (ProfilerInterceptor.ReentrancyCounter > 0) { CallOriginal(invocation, false); return; } bool callOriginal = false; ProfilerInterceptor.GuardInternal(() => { var mockInvocation = new Invocation(invocation.Proxy, invocation.GetConcreteMethod(), invocation.Arguments); DebugView.TraceEvent(IndentLevel.Dispatch, () => String.Format("Intercepted DP call: {0}", mockInvocation.InputToString())); DebugView.PrintStackTrace(); var mock = MocksRepository.GetMockMixinFromInvocation(mockInvocation); var repo = mock != null ? mock.Repository : this.constructionRepo; lock (repo) { repo.DispatchInvocation(mockInvocation); } invocation.ReturnValue = mockInvocation.ReturnValue; callOriginal = mockInvocation.CallOriginal; if (callOriginal) { DebugView.TraceEvent(IndentLevel.DispatchResult, () => "Calling original implementation"); } else if (mockInvocation.IsReturnValueSet) { DebugView.TraceEvent(IndentLevel.DispatchResult, () => String.Format("Returning value '{0}'", invocation.ReturnValue)); } }); if (callOriginal) { CallOriginal(invocation, true); } }
public static void RaiseEventImpl(object instance, EventInfo evt, object[] args) { if (evt == null) { throw new MockException("Unable to deduce which event was specified in the parameter."); } if (args == null) { args = new object[] { null }; } if (args.Length == 1 && (evt.EventHandlerType.IsGenericType && evt.EventHandlerType.GetGenericTypeDefinition() == typeof(EventHandler <>) || evt.EventHandlerType == typeof(EventHandler) || args[0] is EventArgs) ) { args = new[] { instance, args[0] }; } if (!(instance is IMockMixin)) { var mockMixin = MocksRepository.GetMockMixin(instance, evt.DeclaringType); if (mockMixin != null) { instance = mockMixin; } } var mixin = instance as IEventsMixin; if (mixin != null) { mixin.RaiseEvent(evt, args); } else { MockingUtil.RaiseEventThruReflection(instance, evt, args); } }
internal static CallPattern FromAction(MocksRepository repository, Action memberAction, bool dispatchToMethodMocks = false) { var callPattern = new CallPattern(); Invocation lastInvocation = null; var recorder = new DelegatingRecorder(); recorder.Record += invocation => lastInvocation = invocation; using (repository.StartRecording(recorder, dispatchToMethodMocks)) { memberAction(); } if (lastInvocation == null) { throw new MockException("The specified action did not call a mocked method."); } callPattern.SetMethod(lastInvocation.Method, checkCompatibility: true); callPattern.InstanceMatcher = new ReferenceMatcher(lastInvocation.Instance); // Because it's impossible to distinguish between a literal value passed as an argument and // one coming from a matcher, it is impossible to tell exactly which arguments are literal and which are matchers. // So, we assume that the user always first specifies some literal values, and then some matchers. // We assume that the user will never pass a literal after a matcher. using (repository.StartArrangeArgMatching()) { for (int i = 0; i < lastInvocation.Args.Length; ++i) { var indexInMatchers = i - (lastInvocation.Args.Length - repository.MatchersInContext.Count); var matcher = indexInMatchers >= 0 ? repository.MatchersInContext[indexInMatchers] : new ValueMatcher(lastInvocation.Args[i]); callPattern.ArgumentMatchers.Add(matcher); } } repository.MatchersInContext.Clear(); callPattern.AdjustForExtensionMethod(); return(callPattern); }
public override MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior) { var stackTrace = new StackTrace(); var frames = stackTrace.EnumerateFrames().ToList(); var testMethod = FindExistingTestMethod(frames); if (testMethod != null) return repositories[testMethod.DeclaringType]; if (unresolvedContextBehavior == UnresolvedContextBehavior.DoNotCreateNew) return null; var caller = frames.FirstOrDefault(method => method.Module.Assembly != typeof(MocksRepository).Assembly); var mspecTestClass = caller.DeclaringType; MocksRepository parentRepo; repositories.TryGetValue(mspecTestClass.BaseType, out parentRepo); var repo = new MocksRepository(parentRepo, caller); repositories.Add(mspecTestClass, repo); return repo; }
public override bool RetireRepository() { RepositoryOperationsBase entryOps = null; int repoIdx; var testMethod = FindTestMethod(out repoIdx, out entryOps); if (testMethod == null) { return(false); } var entryKey = entryOps.GetKey(testMethod); MocksRepository repo = FindRepositoryInOps(entryOps, entryKey); if (repo != null) { entryOps.RetireRepository(entryKey, repo); } return(true); }
public override void AddRepository(object entryKey, MocksRepository entryRepo) { this.GetCurrentDictionary().Add(entryKey, new WeakReference(entryRepo)); #if !PORTABLE try { if (MockingContext.Plugins.Exists <IDebugWindowPlugin>()) { var debugWindowPlugin = MockingContext.Plugins.Get <IDebugWindowPlugin>(); debugWindowPlugin.RepositoryCreated( entryRepo.RepositoryId, entryRepo.GetRepositoryPath(), new MethodMockInfo(entryRepo.Method.Name, entryRepo.Method.MemberType, entryRepo.Method.DeclaringType, entryRepo.Method.ReflectedType)); } } catch (Exception e) { System.Diagnostics.Trace.WriteLine("Exception thrown calling IDebugWindowPlugin plugin: " + e); } #endif }
public void Process(Invocation invocation) { if (invocation.Recording || invocation.InArrange || invocation.InAssertSet) { return; } var returnType = invocation.Method.GetReturnType(); if (!typeof(Task).IsAssignableFrom(returnType)) { MockingContext.Fail("Wrong invocation to arrangement: return type of {0}.{1} is not a task", invocation.Instance != null ? MockingUtil.GetUnproxiedType(invocation.Instance) : invocation.Method.DeclaringType, invocation.Method.Name); } var elementType = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>) ? returnType.GetGenericArguments()[0] : typeof(object); Expression <Func <Task <object> > > taskFromException = () => MockingUtil.TaskFromException <object>((Exception)null); var mock = ((MethodCallExpression)taskFromException.Body).Method .GetGenericMethodDefinition() .MakeGenericMethod(elementType) .Invoke(null, new object[] { this.exception }); var parentMock = invocation.MockMixin; var mockMixin = MocksRepository.GetMockMixin(mock, null); if (parentMock != null && mockMixin != null) { parentMock.DependentMocks.Add(mock); } invocation.ReturnValue = mock; invocation.CallOriginal = false; invocation.UserProvidedImplementation = true; }
public static void UnregisterGlobalInterceptor(MethodBase method, MocksRepository repo) { throw new NotSupportedException(); }
public object Create(Type type, MocksRepository repository, IMockMixin mockMixinImpl, MockCreationSettings settings, bool createTransparentProxy) { var options = new ProxyGenerationOptions(); options.AddMixinInstance(mockMixinImpl); foreach (var mixin in settings.Mixins) options.AddMixinInstance(mixin); if (settings.AdditionalProxyTypeAttributes != null) { foreach (var attr in settings.AdditionalProxyTypeAttributes) { options.AdditionalAttributes.Add(attr); } } var interceptor = repository.Interceptor; #if SILVERLIGHT options.Hook = new ProxyGenerationHook(false, settings.InterceptorFilter); #else options.Hook = new ProxyGenerationHook(settings.MockConstructorCall, settings.InterceptorFilter); #endif object instance = null; Exception proxyFailure = null; if (type.IsInterface) { if (settings.Args != null && settings.Args.Length > 0) throw new ArgumentException("Do not supply contructor arguments when mocking an interface or delegate."); try { instance = generator.CreateInterfaceProxyWithoutTarget(type, settings.AdditionalMockedInterfaces, options, interceptor); } catch (TypeLoadException ex) { proxyFailure = ex; } catch (GeneratorException ex) { proxyFailure = ex; } } else { try { #if SILVERLIGHT if (settings.Args == null || settings.Args.Length == 0) { ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (!constructors.Any(constr => constr.GetParameters().Length == 0)) { var constructorToCall = constructors.FirstOrDefault(); if (constructorToCall != null) { var @params = constructorToCall.GetParameters(); settings.Args = new object[@params.Length]; for (int i = 0; i < @params.Length; ++i) { var p = @params[i]; settings.Args[i] = Convert.IsDBNull(p.DefaultValue) ? p.ParameterType.GetDefaultValue() : p.DefaultValue; } } } } #endif instance = generator.CreateClassProxy(type, settings.AdditionalMockedInterfaces, options, settings.Args, interceptor); } catch (TypeLoadException ex) { proxyFailure = ex; } catch (GeneratorException ex) { proxyFailure = ex; } catch (InvalidProxyConstructorArgumentsException ex) { proxyFailure = ex; if (!settings.MockConstructorCall) throw new MockException(ex.Message); } } if (proxyFailure != null) { throw new ProxyFailureException(proxyFailure); } return instance; }
public ProxyTypeInfo CreateClassProxyType(Type classToProxy, MocksRepository repository, MockCreationSettings settings, MockMixin mockMixinImpl) { var pgo = CreateProxyGenerationOptions(classToProxy, settings, mockMixinImpl); var typeInfo = new ProxyTypeInfo { ProxyType = generator.ProxyBuilder.CreateClassProxyType(classToProxy, Type.EmptyTypes, pgo) }; typeInfo.Mixins.Add(typeof(IInterceptor), repository.Interceptor); foreach (var mixin in pgo.MixinData.MixinInterfaces) { typeInfo.Mixins.Add(mixin, pgo.MixinData.GetMixinInstance(mixin)); } return typeInfo; }
private object CreateMock(Type returnType, MocksRepository repository, Invocation invocation) { var parentMock = invocation.MockMixin; var replicator = parentMock as IMockReplicator; object mock = null; if (returnType.IsArray) { mock = Array.CreateInstance(returnType.GetElementType(), Enumerable.Repeat(0, returnType.GetArrayRank()).ToArray()); } var idictionaryType = returnType.GetImplementationOfGenericInterface(typeof(IDictionary<,>)); if (mock == null && idictionaryType != null) { var dictType = typeof(Dictionary<,>).MakeGenericType(idictionaryType.GetGenericArguments()); mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(dictType)); } var ienumerableType = returnType.GetImplementationOfGenericInterface(typeof(IEnumerable<>)); if (mock == null && ienumerableType != null) { var listType = typeof(List<>).MakeGenericType(ienumerableType.GetGenericArguments()); mock = MockCollection.Create(returnType, repository, replicator, (IEnumerable)MockingUtil.CreateInstance(listType)); } if (mock == null && typeof(Task).IsAssignableFrom(returnType)) { var elementType = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>) ? returnType.GetGenericArguments()[0] : typeof(object); var taskResultValue = MustReturnMock(invocation) ? CreateMock(elementType, repository, invocation) : elementType.GetDefaultValue(); Expression<Func<Task<object>>> taskFromResult = () => MockingUtil.TaskFromResult((object)null); mock = ((MethodCallExpression)taskFromResult.Body).Method .GetGenericMethodDefinition() .MakeGenericMethod(elementType) .Invoke(null, new object[] { taskResultValue }); } if (mock == null && MustReturnMock(invocation, checkPropertyOnTestFixture: true)) { if (typeof(String) == returnType) { mock = String.Empty; } else { try { mock = replicator.CreateSimilarMock(repository, returnType, null, true, null); } catch (MockException) { } } } return mock; }
public static object CreateProxy(object wrappedInstance, MocksRepository repository, IMockMixin mockMixin) { var interceptor = new DynamicProxyInterceptor(repository); var realProxy = new MockingProxy((MarshalByRefObject)wrappedInstance, interceptor, mockMixin); return realProxy.GetTransparentProxy(); }
public abstract void RetireRepository(object key, MocksRepository repo);
public override MocksRepository ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior) { RepositoryOperationsBase entryOps = null; int repoIdx; var testMethod = FindTestMethod(out repoIdx, out entryOps); if (testMethod == null) { return(null); } var entryKey = entryOps.GetKey(testMethod); MocksRepository repo = FindRepositoryInOps(entryOps, entryKey); if (repo != null) { return(repo); } if (unresolvedContextBehavior == UnresolvedContextBehavior.DoNotCreateNew) { return(null); } //Check if this is the same kind of method but from a derived class, thus building context. MocksRepository parentRepo = entryOps.FindRepositoryToInherit(testMethod); if (parentRepo == null) { for (var repoIdxParent = repoIdx + 1; parentRepo == null && repoIdxParent < this.repoOperations.Count; ++repoIdxParent) { var ops = this.repoOperations[repoIdxParent]; if (ops.IsLeaf) { continue; } var parentKey = ops.GetKey(testMethod); if (ops.IsUsedOnAllThreads) { parentRepo = ops.FindRepositoryFromAnyThread(parentKey); } else { parentRepo = ops.FindRepository(parentKey) ?? ops.FindRepositoryToInherit(testMethod); } } } MocksRepository entryRepo; try { entryRepo = new MocksRepository(parentRepo, testMethod); entryOps.AddRepository(entryKey, entryRepo); OnMocksRepositoryCreated(repo); } catch (TypeInitializationException e) { throw e.InnerException; } return(entryRepo); }
public abstract void RetireRepository(object key, MocksRepository repo);
public abstract void AddRepository(object entryKey, MocksRepository entryRepo);
protected virtual void OnMocksRepositoryCreated(MocksRepository repo) { }
public static void EnableInterception(Type type, bool enabled, MocksRepository behalf) { throw new NotSupportedException(); }
public MockCollectionBehavior(Type resultCollection, MocksRepository repo, IEnumerable collection) { this.collection = (IEnumerable) MockCollection.Create(resultCollection, repo, null, collection); }
public ProxyTypeInfo CreateClassProxyType(Type classToProxy, MocksRepository repository, MockCreationSettings settings, MockMixin mockMixinImpl) { throw new NotImplementedException("//TODO"); }
protected virtual void OnMocksRepositoryCreated(MocksRepository repo) { }
public static object CreateProxy(object wrappedInstance, MocksRepository repository, IMockMixin mockMixin) { throw new NotSupportedException(); }
public abstract void AddRepository(object entryKey, MocksRepository entryRepo);
public override void AddRepository(object entryKey, MocksRepository entryRepo) { this.GetCurrentDictionary().Add(entryKey, new WeakReference(entryRepo)); }
public override void AddRepository(object entryKey, MocksRepository entryRepo) { this.GetCurrentDictionary().Add(entryKey, new WeakReference(entryRepo)); }
public override void RetireRepository(object key, MocksRepository repo) { var dict = currentRepositories.GetAllThreadsValues().FirstOrDefault(repos => repos.Any(pair => pair.Value.Target == repo)); if (dict != null) { dict.Remove(key); repo.Retire(); } }
public object CreateSimilarMock(MocksRepository repository, Type mockType, object[] constructorArgs, bool mockConstructorCall, Type[] additionalMockedInterfaces) { return repository.Create(mockType, constructorArgs, this.Behavior, additionalMockedInterfaces, mockConstructorCall); }
internal DynamicProxyInterceptor(MocksRepository constructionRepo) { this.constructionRepo = constructionRepo; }