Exemple #1
0
        public override object CreateMock(Type mockType, MocksRepository repository)
        {
            MockCreationSettings settings = MockCreationSettings.GetSettings(this.arguments, this.behavior, this.implementedInterfaces.ToArray(),
                                                                             this.mockConstructor, this.additionalProxyTypeAttributes, null, null, null, this.interceptorFilter);

            return(repository.Create(mockType, settings));
        }
Exemple #2
0
 /// <summary>
 /// Setups the target for mocking all static calls.
 /// </summary>
 /// <param name="staticType">Static type</param>
 /// <param name="staticConstructor">Defines the behavior of the static constructor</param>
 public static void SetupStatic(Type staticType, StaticConstructor staticConstructor)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings();
         MockingContext.CurrentRepository.InterceptStatics(staticType, settings, staticConstructor == StaticConstructor.Mocked);
     });
 }
Exemple #3
0
 /// <summary>
 /// Setups the target for mocking all static calls.
 /// </summary>
 /// <param name="staticType">Static type</param>
 public static void SetupStatic(Type staticType)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings();
         MockingContext.CurrentRepository.InterceptStatics(staticType, settings, false);
     });
 }
Exemple #4
0
 /// <summary>
 /// Creates a mock instance from a given type.
 /// </summary>
 /// <param name="type">Mocking type</param>
 /// <param name="behavior">Specifies behavior of the mock. Default is <see cref="Behavior.RecursiveLoose"/></param>
 /// <returns>Mock instance</returns>
 public static object Create(Type type, Behavior behavior)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings(behavior);
         return MockingContext.CurrentRepository.Create(type, settings);
     }));
 }
Exemple #5
0
 /// <summary>
 /// Creates a mocked instance from an internal class.
 /// </summary>
 /// <param name="fullName">Fully qualified name of the target type.</param>
 /// <param name="behavior">Specifies behavior of the mock. Default is <see cref="Behavior.RecursiveLoose"/></param>
 /// <returns>Mock instance</returns>
 public static object Create(string fullName, Behavior behavior)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings(behavior);
         return MockingContext.CurrentRepository.Create(MockingUtil.GetTypeFrom(fullName), settings);
     }));
 }
Exemple #6
0
 /// <summary>
 /// Creates a mocked instance from a given type.
 /// </summary>
 /// <param name="constructor">
 /// Specifies whether to call the base constructor
 /// </param>
 /// <param name="behavior">Specifies behavior of the mock. Default is <see cref="Behavior.RecursiveLoose"/></param>
 /// <returns>Mock instance</returns>
 /// <typeparam name="T">Target type</typeparam>
 public static T Create <T>(Constructor constructor, Behavior behavior)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings(null, behavior, null, constructor == Constructor.Mocked);
         return (T)MockingContext.CurrentRepository.Create(typeof(T), settings);
     }));
 }
Exemple #7
0
 /// <summary>
 /// Creates a mocked instance from a given type with <see cref="Behavior.RecursiveLoose"/> behavior.
 /// </summary>
 /// <param name="target">Target to mock</param>
 /// <param name="args">Constructor arguments</param>
 /// <returns>Mock instance</returns>
 public static object Create(Type target, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings(args, null, null, null);
         return MockingContext.CurrentRepository.Create(target, settings);
     }));
 }
Exemple #8
0
 /// <summary>
 /// Creates a mocked instance from a given type with <see cref="Behavior.RecursiveLoose"/> behavior.
 /// </summary>
 /// <typeparam name="T">Type of the mock</typeparam>
 /// <returns>Mock instance</returns>
 public static T Create <T>()
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings();
         return (T)MockingContext.CurrentRepository.Create(typeof(T), settings);
     }));
 }
Exemple #9
0
 /// <summary>
 /// Setups the target for mocking all static calls.
 /// </summary>
 /// <remarks>
 /// Considers all public members of the class. To mock private member,
 /// please use the private interface Mock.NonPublic
 /// </remarks>
 /// <param name="behavior">
 /// Specifies behavior of the mock. Default is <see cref="Behavior.RecursiveLoose"/>
 /// </param>
 /// <typeparam name="T">
 /// Target type
 /// </typeparam>
 public static void SetupStatic <T>(Behavior behavior)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings(behavior);
         MockingContext.CurrentRepository.InterceptStatics(typeof(T), settings, false);
     });
 }
Exemple #10
0
 /// <summary>
 /// Creates a mocked instance from a given type.
 /// </summary>
 /// <typeparam name="T">Type of the mock</typeparam>
 /// <param name="behavior">Specifies behavior of the mock. Default is <see cref="Behavior.RecursiveLoose"/></param>
 /// <param name="args">Constructor arguments</param>
 /// <returns>Mock instance</returns>
 public static T Create <T>(Behavior behavior, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockCreationSettings settings = MockCreationSettings.GetSettings(args, behavior, null, null);
         return (T)MockingContext.CurrentRepository.Create(typeof(T), settings);
     }));
 }
		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;
			}
		}
Exemple #12
0
        public void Process(Invocation invocation)
        {
            var mockMixin = invocation.MockMixin;

            if (mockMixin == null)
            {
                MockCreationSettings settings = MockCreationSettings.GetSettings(Behavior.CallOriginal);
                mockMixin = invocation.Repository.CreateExternalMockMixin(null, invocation.Instance, settings);
                mockMixin.IsInstanceConstructorMocked = true;
            }

            invocation.CallOriginal = !mockMixin.IsInstanceConstructorMocked;
        }
Exemple #13
0
 private static T CreateFromNew <T>(Expression <Func <T> > expression, Behavior?behavior)
 {
     try
     {
         var args = expression.GetArgumentsFromConstructorExpression();
         MockCreationSettings settings = MockCreationSettings.GetSettings(args, behavior, null, false);
         return((T)MockingContext.CurrentRepository.Create(typeof(T), settings));
     }
     catch (InvalidCastException e)
     {
         throw new MockException("The constructor expression was not of the correct form. It should be a 'new' expression.", e);
     }
 }
        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 ProxyTypeInfo CreateClassProxyType(Type classToProxy, MocksRepository repository, MockCreationSettings settings, MockMixin mockMixinImpl)
 {
     throw new NotImplementedException("//TODO");
 }
		private ProxyGenerationOptions CreateProxyGenerationOptions(Type type, MockCreationSettings settings, MockMixin mockMixinImpl = null)
		{
			var options = new ProxyGenerationOptions();
			if (mockMixinImpl != null)
				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);
				}
			}

			return options;
		}
        public object CreateSimilarMock(MocksRepository repository, Type mockType, object[] constructorArgs, bool mockConstructorCall, Type[] additionalMockedInterfaces)
        {
            MockCreationSettings settings = MockCreationSettings.GetSettings(constructorArgs, this.Behavior, additionalMockedInterfaces, mockConstructorCall);

            return(repository.Create(mockType, settings));
        }
		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;
		}
		public ProxyTypeInfo CreateClassProxyType(Type classToProxy, MocksRepository repository, MockCreationSettings settings, MockMixin mockMixinImpl)
		{
			throw new NotImplementedException("//TODO");
		}
		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;
		}
Exemple #21
0
        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);
                IMockMixin mockMixin = MocksRepository.GetMockMixin(mock, null);
                mockMixin.FallbackBehaviors.Insert(0, queryableBehavior);
                mockMixin.FallbackBehaviors.Insert(0, listBehavior);
                return(mock);
            }
            else
            {
                MockCreationSettings settings = MockCreationSettings.GetSettings(constructorArgs: null, behavior: Behavior.Loose, additionalMockedInterfaces: MockingUtil.EmptyTypes, mockConstructorCall: null,
                                                                                 additionalProxyTypeAttributes: null, supplementaryBehaviors: null, fallbackBehaviors: new List <IBehavior> {
                    listBehavior, queryableBehavior
                });

                return(repo.Create(resultCollectionType, settings));
            }
        }