示例#1
0
        internal static PropertyInfo ResolveProperty(Type type, string name, bool ignoreCase, object[] indexArgs, bool hasInstance, object setterValue = null, bool getter = true)
        {
            var candidates = type.GetAllProperties().Where(prop => MockingUtil.StringEqual(prop.Name, name, ignoreCase)).ToArray();

            if (candidates.Length == 1)
            {
                return(candidates[0]);
            }

            if (!getter)
            {
                Array.Resize(ref indexArgs, indexArgs.Length + 1);
                indexArgs[indexArgs.Length - 1] = setterValue;
            }

            var propMethods = candidates
                              .Select(prop => getter ? prop.GetGetMethod(true) : prop.GetSetMethod(true))
                              .Where(m => m != null && CanCall(m, hasInstance))
                              .ToArray();

            indexArgs = indexArgs ?? MockingUtil.NoObjects;
            object state;
            var    foundGetter = MockingUtil.BindToMethod(MockingUtil.AllMembers, propMethods, ref indexArgs, null, null, null, out state);

            return(candidates.First(prop => (getter ? prop.GetGetMethod(true) : prop.GetSetMethod(true)) == foundGetter));
        }
示例#2
0
        private AssemblyName GetAssemblyName(bool signStrongName)
        {
            var keyPairStream = signStrongName ? GetKeyPair() : null;
            var name          = signStrongName ? strongAssemblyName : weakAssemblyName;

            return(MockingUtil.GetStrongAssemblyName(name, keyPairStream));
        }
        public static string FormatValue(object value)
        {
            if (value == null)
            {
                return("null");
            }

            if (value is string)
            {
                return(String.Format("\"{0}\"", value));
            }

            if (value is char)
            {
                return(String.Format("'{0}'", value));
            }

            var    valueType = MockingUtil.GetUnproxiedType(value);
            string valueStr  = valueType.ToString();

            try
            {
                valueStr = value.ToString();
            }
            catch { }

            if (valueStr == valueType.ToString())
            {
                return(valueStr);
            }

            return(String.Format("({0}) {1}", valueType.GetShortCSharpName(), valueStr));
        }
示例#4
0
            public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
            {
                var callResult = Expression.Variable(typeof(object));
                var argsVar    = Expression.Variable(typeof(object[]));

                MethodInfo invoke     = typeof(PrivateAccessor).GetMethod("CallMethod", new[] { typeof(string), typeof(object[]) });
                var        invokeArgs = new List <Expression>
                {
                    Expression.Constant(binder.Name),
                    argsVar
                };

                var typeArgs = MockingUtil.TryGetTypeArgumentsFromBinder(binder);

                if (typeArgs != null)
                {
                    invoke = typeof(PrivateAccessor).GetMethod("CallMethodWithTypeArguments");
                    invokeArgs.Insert(1, Expression.Constant(typeArgs));
                }

                var executionList = new List <Expression>
                {
                    Expression.Assign(argsVar, Expression.NewArrayInit(typeof(object), args.Select(a => Expression.Convert(a.Expression, typeof(object))))),
                    Expression.Assign(callResult, Expression.Call(
                                          Expression.Convert(this.Expression, typeof(PrivateAccessor)), invoke, invokeArgs.ToArray())),
                };

                executionList.AddRange(args
                                       .Select((a, i) => new { expr = a.Expression, i })
                                       .Where(p => p.expr is ParameterExpression)
                                       .Select(p => Expression.Assign(p.expr, Expression.Convert(Expression.ArrayIndex(argsVar, Expression.Constant(p.i)), p.expr.Type))));
                executionList.Add(callResult);

                return(CreateMetaObject(Expression.Block(new[] { argsVar, callResult }, executionList)));
            }
        public ImplementationOverrideBehavior(Delegate implementationOverride, bool ignoreDelegateReturnValue)
        {
            this.ignoreDelegateReturnValue = ignoreDelegateReturnValue;
            this.implementationOverride    = implementationOverride;

            this.overrideInvoker = MockingUtil.MakeFuncCaller(implementationOverride);
        }
示例#6
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(() =>
     {
         return MockingContext.CurrentRepository.Create(MockingUtil.GetTypeFrom(fullName), null, behavior, null, null);
     }));
 }
        public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
        {
            var wrapper   = this.Value as ExpressionContainer;
            var valueExpr = wrapper.Expression;

            var typeArgs = MockingUtil.TryGetTypeArgumentsFromBinder(binder);

            var candidateMethods = valueExpr.Type.GetAllMethods()
                                   .Where(m => MockingUtil.StringEqual(m.Name, binder.Name, binder.IgnoreCase) && m.IsStatic == wrapper.IsStatic)
                                   .Where(m => m.GetParameters().Length >= args.Length)
                                   .Select(m =>
            {
                if (typeArgs == null)
                {
                    return(MockingUtil.TrySpecializeGenericMethod(m, args.Select(a => a.RuntimeType).ToArray()) ?? m);
                }
                else
                {
                    return(MockingUtil.TryApplyTypeArguments(m, typeArgs));
                }
            })
                                   .Where(m => m != null)
                                   .Where(m =>
            {
                var methodParams = m.GetParameters();
                for (int i = 0; i < args.Length; ++i)
                {
                    var matcher = UnwrapMatcher(args[i]);
                    if (matcher != null)
                    {
                        var argType = matcher.ReturnType;
                        if (!methodParams[i].ParameterType.IsAssignableFrom(argType))
                        {
                            return(false);
                        }
                    }
                }
                return(true);
            })
                                   .ToArray();

            if (candidateMethods.Length == 0 && args.Length == 0)
            {
                return(DoBindGetMember(binder.ReturnType, binder.Name, binder.IgnoreCase));
            }

            var methodArgs = args.Select(a =>
            {
                var matcher = UnwrapMatcher(a);
                return(matcher != null ? matcher.ReturnType.GetDefaultValue() : a.Value);
            }).ToArray();

            object state;
            var    method = (MethodInfo)MockingUtil.BindToMethod(MockingUtil.Default, candidateMethods, ref methodArgs, null, null, null, out state);

            var memberExpr = Expression.Call(!wrapper.IsStatic ? valueExpr : null, method, args.Select(FromArg).ToArray());

            return(CreateRecorder(memberExpr, binder.ReturnType, BindingRestrictions.GetInstanceRestriction(this.Expression, this.Value)));
        }
示例#8
0
 internal static object IsAny(Type type, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MockingContext.CurrentRepository.AddMatcherInContext(new TypeMatcher(type));
         return MockingUtil.CreateInstance(type, args);
     }));
 }
 /// <summary>
 /// Sets the value of a property by name.
 /// </summary>
 /// <param name="name">The name of the property.</param>
 /// <param name="value">The value to set to the property.</param>
 /// <param name="indexArgs">Optional index arguments if the property has any.</param>
 public void SetProperty(string name, object value, params object[] indexArgs)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var prop = MockingUtil.ResolveProperty(this.type, name, false, indexArgs, this.instance != null, value, getter: false);
         ProfilerInterceptor.GuardExternal(() => SecuredReflectionMethods.SetProperty(prop, this.instance, value, indexArgs));
     });
 }
示例#10
0
 public void Raise(object instance, string eventName, params object[] args)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         RaiseEventBehavior.RaiseEventImpl(instance, MockingUtil.GetUnproxiedType(instance).GetEvent(eventName,
                                                                                                     BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance), args);
     });
 }
示例#11
0
 /// <summary>
 /// Throws a the specified exception for the target async call causing returned task to fail.
 /// </summary>
 /// <returns></returns>
 public IAssertable ThrowsAsync <T>(params object[] args) where T : Exception
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         this.behaviors.Add(new ThrowAsyncExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T), args)));
         return this;
     }));
 }
示例#12
0
 /// <summary>
 /// Throws a the specified expection for target call.
 /// </summary>
 /// <returns></returns>
 public IAssertable Throws <T>() where T : Exception
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         this.behaviors.Add(new ThrowExceptionBehavior((T)MockingUtil.CreateInstance(typeof(T))));
         return this;
     }));
 }
 public void Assert(object target, MethodInfo method, Occurs occurs, params object[] args)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var message = MockingUtil.GetAssertionMessage(args);
         MockingContext.CurrentRepository.AssertMethodInfo(message, target, method, args, occurs);
     });
 }
 public void Assert(MethodBase method, params object[] args)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var message = MockingUtil.GetAssertionMessage(args);
         MockingContext.CurrentRepository.AssertMethodInfo(message, null, method, args, null);
     });
 }
 public ActionExpectation Arrange(Type targetType, string memberName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         var method = MockingUtil.GetMethodByName(targetType, typeof(void), memberName, ref args);
         return MockingContext.CurrentRepository.Arrange(null, method, args, () => new ActionExpectation());
     }));
 }
 public FuncExpectation <TReturn> Arrange <T, TReturn>(string memberName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         var method = MockingUtil.GetMethodByName(typeof(T), typeof(TReturn), memberName, ref args);
         return MockingContext.CurrentRepository.Arrange(null, method, args, () => new FuncExpectation <TReturn>());
     }));
 }
示例#17
0
 /// <summary>
 /// Raises the specified event passing the given arguments to the handlers.
 /// </summary>
 /// <param name="name">The name of the event to raise.</param>
 /// <param name="eventArgs">Arguments to pass to the event handlers. Must match the event handler signature exactly.</param>
 public void RaiseEvent(string name, params object[] eventArgs)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var evt = this.type.GetEvent(name, MockingUtil.AllMembers);
         MockingUtil.RaiseEventThruReflection(this.instance, evt, eventArgs);
     });
 }
 public int GetTimesCalled(Type type, string memberName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         var method = MockingUtil.GetMethodByName(type, typeof(void), memberName, ref args);
         return MockingContext.CurrentRepository.GetTimesCalledFromMethodInfo(null, method, args);
     }));
 }
示例#19
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);
     }));
 }
示例#20
0
 public FuncExpectation <TReturn> Arrange <TReturn>(object target, string methodName, Type[] memberParamTypes, string localFunctionName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, memberParamTypes);
         return this.Arrange <TReturn>(target, method, localFunctionName, args);
     }));
 }
 /// <summary>
 /// Gets the value of a property by name.
 /// </summary>
 /// <param name="name">The name of the property.</param>
 /// <param name="indexArgs">Optional index arguments if the property has any.</param>
 /// <returns>The value of the property.</returns>
 public object GetProperty(string name, params object[] indexArgs)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         var prop = MockingUtil.ResolveProperty(this.type, name, false, indexArgs, this.instance != null);
         return ProfilerInterceptor.GuardExternal(() => SecuredReflectionMethods.GetProperty(prop, this.instance, indexArgs));
     }));
 }
示例#22
0
 public ActionExpectation Arrange(Type type, string methodName, Type[] methodParamTypes, string localMemberName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MethodInfo method = MockingUtil.GetMethodWithLocalFunction(type, methodName, methodParamTypes);
         return this.Arrange(type, method, localMemberName, args);
     }));
 }
示例#23
0
 public ActionExpectation Arrange(object target, MethodInfo method, string localFunctionName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MethodInfo localMethod = MockingUtil.GetLocalFunction(target, method, localFunctionName);
         return Mock.NonPublic.Arrange(target, localMethod, args);
     }));
 }
示例#24
0
 public void Assert(object target, string methodName, Type[] methodParamTypes, string localFunctionName, params object[] args)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         MethodInfo method = MockingUtil.GetMethodWithLocalFunction(target, methodName, methodParamTypes);
         this.Assert(target, method, localFunctionName, args);
     });
 }
示例#25
0
 public FuncExpectation <TReturn> Arrange <TReturn>(Type type, MethodInfo method, string localFunctionName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         MethodInfo localMethod = MockingUtil.GetLocalFunction(type, method, localFunctionName);
         return Mock.NonPublic.Arrange <TReturn>(type, localMethod, args);
     }));
 }
示例#26
0
 public object Call(object target, MethodInfo method, string localFunctionName, params object[] args)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         Type type = target.GetType();
         MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName);
         return Mock.NonPublic.MakePrivateAccessor(target).CallMethod(localFunction, args);
     }));
 }
 public void Assert(Type targetType, string memberName, Occurs occurs, params object[] args)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var message = MockingUtil.GetAssertionMessage(args);
         var method  = MockingUtil.GetMethodByName(targetType, typeof(void), memberName, ref args);
         MockingContext.CurrentRepository.AssertMethodInfo(message, null, method, args, occurs);
     });
 }
 void INonPublicExpectation.Assert <TReturn>(Type targetType, string memberName, params object[] args)
 {
     ProfilerInterceptor.GuardInternal(() =>
     {
         var message = MockingUtil.GetAssertionMessage(args);
         var method  = MockingUtil.GetMethodByName(targetType, typeof(TReturn), memberName, ref args);
         MockingContext.CurrentRepository.AssertMethodInfo(message, null, method, args, null);
     });
 }
示例#29
0
 /// <summary>
 /// Creates a mocked instance from an internal class.
 /// </summary>
 /// <param name="fullName">Fully qualified name of the target type.</param>
 /// <param name="settings">Settings for the mock</param>
 /// <returns>Mock instance</returns>
 public static object Create(string fullName, Action <IFluentConfig> settings)
 {
     return(ProfilerInterceptor.GuardInternal(() =>
     {
         var fluentConfig = new FluentConfig();
         settings(fluentConfig);
         return fluentConfig.CreateMock(MockingUtil.GetTypeFrom(fullName), MockingContext.CurrentRepository);
     }));
 }
示例#30
0
        public void Assert(object target, MethodInfo method, string localFunctionName, Occurs occurs, params object[] args)
        {
            ProfilerInterceptor.GuardInternal(() =>
            {
                Type type = target.GetType();
                MethodInfo localFunction = MockingUtil.GetLocalFunction(type, method, localFunctionName);

                Mock.NonPublic.Assert(target, localFunction, occurs, args);
            });
        }