コード例 #1
0
ファイル: PropertyBehavior.cs プロジェクト: v-prla/moq
        /// <summary>
        /// Gets or sets the value of the given property as an entry in the mock <see cref="IMock.State"/>.
        /// </summary>
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            if (invocation == null)
            {
                throw new ArgumentNullException(nameof(invocation));
            }

            var state = (invocation.Target as IMocked ?? throw new ArgumentException(ThisAssembly.Strings.TargetNotMock, nameof(invocation)))
                        .Mock.State;

            if (invocation.MethodBase.Name.StartsWith("get_", StringComparison.Ordinal) &&
                state.TryGetValue <object>("_" + invocation.MethodBase.Name.Substring(4), out var value))
            {
                return(invocation.CreateValueReturn(value));
            }

            if (invocation.MethodBase.Name.StartsWith("set_", StringComparison.Ordinal) &&
                (!SetterRequiresSetup || SetupScope.IsActive))
            {
                state.Set("_" + invocation.MethodBase.Name.Substring(4), invocation.Arguments.GetValue(0));
                return(invocation.CreateValueReturn(null));
            }

            return(next()(invocation, next));
        }
コード例 #2
0
        /// <inheritdoc />
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            var info = invocation.MethodBase.DeclaringType.GetRuntimeEvent(
                invocation.MethodBase.Name.Replace("add_", string.Empty).Replace("remove_", string.Empty));

            if (info != null)
            {
                if (CallContext <EventRaiser> .GetData() is EventRaiser raiser)
                {
                    try
                    {
                        var mock = ((IMocked)invocation.Target).Mock;
                        mock.Invocations.Remove(invocation);
                        if (mock.State.TryGetValue <Delegate>(info.Name, out var handler) &&
                            handler != null)
                        {
                            switch (raiser)
                            {
                            case EmptyEventRaiser _:
                                handler.DynamicInvoke(invocation.Target, EventArgs.Empty);
                                break;

                            case EventArgsEventRaiser a:
                                handler.DynamicInvoke(invocation.Target, a.EventArgs);
                                break;

                            case CustomEventRaiser c:
                                handler.DynamicInvoke(c.Arguments);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    finally
                    {
                        CallContext <EventRaiser> .SetData(null);
                    }
                }
                else
                {
                    if (invocation.Arguments.Count == 1 &&
                        invocation.Arguments.GetValue(0) is Delegate handler)
                    {
                        var mock = ((IMocked)invocation.Target).Mock;
                        if (invocation.MethodBase.Name.StartsWith("add_", StringComparison.Ordinal))
                        {
                            CombineDelegate(info, handler, mock);
                        }
                        else
                        {
                            RemoveDelegate(info, handler, mock);
                        }
                    }
                }
            }

            return(next()(invocation, next));
        }
コード例 #3
0
ファイル: MockBehavior.cs プロジェクト: moq/moq.proxy
		public IMethodReturn Invoke (IMethodInvocation invocation, GetNextBehavior getNext)
		{
			// This is where the whole Moq matching, behavior, callbacks etc. 
			// would be evaluated and provide the actual behavior.
			if (invocation.MethodBase.DeclaringType.GetTypeInfo ().IsInterface)
				return invocation.CreateValueReturn (null);

			return getNext () (invocation, getNext);
		}
コード例 #4
0
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            // This is where the whole Moq matching, behavior, callbacks etc.
            // would be evaluated and provide the actual behavior.
            if (invocation.MethodBase.DeclaringType.GetTypeInfo().IsInterface)
            {
                return(invocation.CreateValueReturn(null));
            }

            return(getNext() (invocation, getNext));
        }
コード例 #5
0
        /// <inheritdoc />
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            var arguments  = invocation.Arguments.ToArray();
            var parameters = invocation.MethodBase.GetParameters();

            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];
                // This covers both out & ref
                if (parameter.ParameterType.IsByRef)
                {
                    arguments[i] = DefaultValue.For(parameter.ParameterType);
                }
            }

            var returnValue = default(object);

            if (invocation.MethodBase is MethodInfo info &&
                info.ReturnType != typeof(void))
            {
                returnValue = DefaultValue.For(info.ReturnType);
            }

            return(invocation.CreateValueReturn(returnValue, arguments));
        }
コード例 #6
0
ファイル: MockTrackingBehavior.cs プロジェクト: wmadzha/moq
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            var mock = invocation.Target.GetMock();

            // Allows subsequent extension methods on the fluent API to retrieve the
            // current invocation being performed via the MockContext.
            CallContext <IMethodInvocation> .SetData(invocation);

            // Determines the current setup according to contextual
            // matchers that may have been pushed to the MockSetup context.
            // Allows subsequent extension methods on the fluent API to retrieve the
            // current setup being performed via the MockContext.
            CallContext <IMockSetup> .SetData(MockSetup.Freeze(invocation));

            // Don't record the invocation if it's performed within a setup scope.
            if (!SetupScope.IsActive)
            {
                mock.Invocations.Add(invocation);
            }

            // While debugging, capture invocation stack traces for easier
            // troubleshooting
            if (Debugger.IsAttached)
            {
                invocation.Context["StackTrace"] = Environment.StackTrace;
            }

            return(getNext().Invoke(invocation, getNext));
        }
コード例 #7
0
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            if (invocation.MethodBase.DeclaringType == typeof(IMocked))
            {
                return(invocation.CreateValueReturn(this));
            }

            CallContext <IMethodInvocation> .SetData(nameof(IMethodInvocation), invocation);

            Invocations.Add(invocation);

            if (Behaviors.Count == 0)
            {
                return(getNext().Invoke(invocation, getNext));
            }

            // This is the only added functionality of this behavior, to first match
            // applicable InvokeBehaviors and execute them in sequence.
            var applicableBehaviors = Behaviors.Where(behavior => behavior.AppliesTo(invocation)).ToArray();

            if (applicableBehaviors.Length == 0)
            {
                return(getNext().Invoke(invocation, getNext));
            }

            var index = 0;

            return(applicableBehaviors[0].Invoke(invocation, () =>
            {
                ++index;
                return (index < applicableBehaviors.Length) ?
                applicableBehaviors[index].Invoke :
                getNext();
            }));
        }
コード例 #8
0
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            // Allows subsequent extension methods on the fluent API to retrieve the
            // current invocation being performed.
            CallContext <IMethodInvocation> .SetData(invocation);

            // Determines the current setup according to contextual
            // matchers that may have been pushed to the MockSetup context.
            // Allows subsequent extension methods on the fluent API to retrieve the
            // current setup being performed.
            var setup = MockSetup.Freeze(invocation);

            CallContext <IMockSetup> .SetData(setup);

            var mock = invocation.Target is IMocked mocked ?
                       mocked.Mock : throw new ArgumentException(Resources.TargetNotMocked);

            mock.Invocations.Add(invocation);
            if (mock is MockInfo info)
            {
                info.LastSetup = setup;
            }

            return(getNext().Invoke(invocation, getNext));
        }
コード例 #9
0
ファイル: DefaultValueBehavior.cs プロジェクト: wmadzha/moq
        /// <summary>
        /// Fills in the ref, out and return values with the defaults determined
        /// by the <see cref="DefaultValue"/> utility class.
        /// </summary>
        IMethodReturn IStuntBehavior.Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            var arguments  = invocation.Arguments.ToArray();
            var parameters = invocation.MethodBase.GetParameters();

            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];
                // Only provide default values for out parameters.
                // NOTE: does not touch ByRef values.
                if (parameter.IsOut)
                {
                    arguments[i] = Provider.For(parameter.ParameterType);
                }
            }

            var returnValue = default(object);

            if (invocation.MethodBase is MethodInfo info &&
                info.ReturnType != typeof(void))
            {
                returnValue = Provider.For(info.ReturnType);
            }

            return(invocation.CreateValueReturn(returnValue, arguments));
        }
コード例 #10
0
        /// <summary>
        /// Skips all non-setup behaviors from execution.
        /// </summary>
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            foreach (var behavior in invocation.Target.AsMock().Behaviors.Where(x => !setupScopeBehaviors.Contains(x.GetType())))
            {
                invocation.SkipBehaviors.Add(behavior.GetType());
            }

            return(next().Invoke(invocation, next));
        }
コード例 #11
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual void OnQueryContinueDrag(Glyph?g, QueryContinueDragEventArgs e)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         GetNextBehavior.OnQueryContinueDrag(g, e);
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         behavior.OnQueryContinueDrag(g, e);
     }
 }
コード例 #12
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual void OnGiveFeedback(Glyph?g, GiveFeedbackEventArgs e)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         GetNextBehavior.OnGiveFeedback(g, e);
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         behavior.OnGiveFeedback(g, e);
     }
 }
コード例 #13
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual void OnDragLeave(Glyph?g, EventArgs e)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         GetNextBehavior.OnDragLeave(g, e);
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         behavior.OnDragLeave(g, e);
     }
 }
コード例 #14
0
            public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
            {
                var mock  = invocation.Target.AsMock();
                var setup = MockContext.CurrentSetup ?? CallContext.ThrowUnexpectedNull <IMockSetup>();

                if (mock.Invocations.Where(x => setup.AppliesTo(x)).Any())
                {
                    throw new VerifyException(mock, setup);
                }

                return(next().Invoke(invocation, next));
            }
コード例 #15
0
        /// <summary>
        /// Fills in the ref, out and return values with the defaults determined
        /// by the <see cref="DefaultValue"/> utility class.
        /// </summary>
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            if (invocation.MethodBase.Name == nameof(GetHashCode))
            {
                return(invocation.CreateValueReturn(RuntimeHelpers.GetHashCode(invocation.Target)));
            }
            if (invocation.MethodBase.Name == nameof(Equals))
            {
                return(invocation.CreateValueReturn(object.ReferenceEquals(invocation.Target, invocation.Arguments[0])));
            }

            return(next().Invoke(invocation, next));
        }
コード例 #16
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual bool OnMouseUp(Glyph?g, MouseButtons button)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         return(GetNextBehavior.OnMouseUp(g, button));
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         return(behavior.OnMouseUp(g, button));
     }
     else
     {
         return(false);
     }
 }
コード例 #17
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual bool OnMouseLeave(Glyph?g)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         return(GetNextBehavior.OnMouseLeave(g));
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         return(behavior.OnMouseLeave(g));
     }
     else
     {
         return(false);
     }
 }
コード例 #18
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual bool OnMouseHover(Glyph?g, Point mouseLoc)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         return(GetNextBehavior.OnMouseHover(g, mouseLoc));
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         return(behavior.OnMouseHover(g, mouseLoc));
     }
     else
     {
         return(false);
     }
 }
コード例 #19
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual bool OnMouseDoubleClick(Glyph?g, MouseButtons button, Point mouseLoc)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         return(GetNextBehavior.OnMouseDoubleClick(g, button, mouseLoc));
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         return(behavior.OnMouseDoubleClick(g, button, mouseLoc));
     }
     else
     {
         return(false);
     }
 }
コード例 #20
0
ファイル: RecordingBehavior.cs プロジェクト: ajaishankar/moq
    public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
    {
        var result = getNext().Invoke(invocation, getNext);

        if (result != null)
        {
            invocations.Add(result);
        }
        else
        {
            invocations.Add(invocation);
        }

        return(result);
    }
コード例 #21
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual void OnDragOver(Glyph?g, DragEventArgs e)
 {
     if (_callParentBehavior && GetNextBehavior != null)
     {
         GetNextBehavior.OnDragOver(g, e);
     }
     else if (GetGlyphBehavior(g) is Behavior behavior)
     {
         behavior.OnDragOver(g, e);
     }
     else if (e.Effect != DragDropEffects.None)
     {
         e.Effect = (Control.ModifierKeys == Keys.Control) ? DragDropEffects.Copy : DragDropEffects.Move;
     }
 }
コード例 #22
0
ファイル: StrictMockBehavior.cs プロジェクト: wmadzha/moq
        /// <summary>
        /// Throws <see cref="StrictMockException"/>.
        /// </summary>
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            if (invocation == null)
            {
                throw new ArgumentNullException(nameof(invocation));
            }

            if (!SetupScope.IsActive)
            {
                throw new StrictMockException();
            }

            // Otherwise, fallback to returning default values so that
            // the fluent setup API can do its work.
            return(fallback.Invoke(invocation, getNext));
        }
コード例 #23
0
        /// <summary>
        /// Configures the current invocation depending on the <see cref="MockBehavior"/>
        /// specified for the mock.
        /// </summary>
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            var moq = invocation.Target.AsMoq();

            if (moq.Behavior != MockBehavior.Strict)
            {
                invocation.SkipBehaviors.Add(typeof(StrictMockBehavior));
            }

            // Ensure the Mock pipeline is always created for the matching setup
            // We need this to skip the StrictBehavior in the CallBaseBehavior
            if (SetupScope.IsActive)
            {
                invocation.Target.AsMock().GetPipeline(MockContext.CurrentSetup);
            }

            return(next().Invoke(invocation, next));
        }
コード例 #24
0
ファイル: Behavior.cs プロジェクト: lukas-lansky/winforms
 public virtual MenuCommand?FindCommand(CommandID commandId)
 {
     try
     {
         if (_callParentBehavior && GetNextBehavior != null)
         {
             return(GetNextBehavior.FindCommand(commandId));
         }
         else
         {
             return(null);
         }
     }
     catch //Catch any exception and return null MenuCommand.
     {
         return(null);
     }
 }
コード例 #25
0
ファイル: CallBaseBehavior.cs プロジェクト: v-prla/moq
        /// <inheritdoc />
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            // Check if CallBase is configured at the Mock or Invocation level
            var shouldCallBase = invocation.Target.AsMoq().CallBase || invocation.Context.ContainsKey(nameof(IMoq.CallBase));

            if (shouldCallBase)
            {
                // Skip the default value to force the base target member is executed
                invocation.SkipBehaviors.Add(typeof(DefaultValueBehavior));

                // If there is a matching setup for the current invocation, skip the strict
                // behavior because CallBase should be called instead
                if (invocation.Target.AsMock().Behaviors.OfType <IMockBehaviorPipeline>().Any(x => x.AppliesTo(invocation)))
                {
                    invocation.SkipBehaviors.Add(typeof(StrictMockBehavior));
                }
            }

            return(next().Invoke(invocation, next));
        }
コード例 #26
0
        /// <summary>
        /// Implements the tracking of invocations for the excuted invocations.
        /// </summary>
        public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next)
        {
            // Allows subsequent extension methods on the fluent API to retrieve the
            // current invocation being performed via the MockContext.
            MockContext.CurrentInvocation = invocation;

            // Determines the current setup according to contextual
            // matchers that may have been pushed to the MockSetup context.
            // Allows subsequent extension methods on the fluent API to retrieve the
            // current setup being performed via the MockContext.
            MockContext.CurrentSetup = MockSetup.Freeze(invocation);

            // While debugging, capture invocation stack traces for easier
            // troubleshooting
            if (Debugger.IsAttached)
            {
                invocation.Context[nameof(Environment.StackTrace)] = invocation.GetStackTrace();
            }

            return(next().Invoke(invocation, next));
        }
コード例 #27
0
ファイル: MockBehavior.cs プロジェクト: ajaishankar/moq
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            // Allows subsequent extension methods on the fluent API to retrieve the
            // current invocation being performed.
            CallContext <IMethodInvocation> .SetData(invocation);

            // Determines the current invocation filter according to contextual
            // matchers that may have been pushed to the Matchers context.
            Matchers.Freeze(invocation);

            var mock = invocation.Target is IMocked mocked ?
                       mocked.Mock : throw new ArgumentException(Resources.TargetNotMocked);

            mock.Invocations.Add(invocation);

            if (mock.Behaviors.Count == 0)
            {
                return(getNext().Invoke(invocation, getNext));
            }

            // This is the only added functionality of this behavior, to first match
            // applicable InvokeBehaviors and execute them in sequence.
            var applicableBehaviors = mock.Behaviors.Where(behavior => behavior.AppliesTo(invocation)).ToArray();

            if (applicableBehaviors.Length == 0)
            {
                return(getNext().Invoke(invocation, getNext));
            }

            var index = 0;

            return(applicableBehaviors[0].Invoke(invocation, () =>
            {
                ++index;
                return (index < applicableBehaviors.Length) ?
                applicableBehaviors[index].Invoke :
                getNext();
            }));
        }
コード例 #28
0
ファイル: StrictMockBehavior.cs プロジェクト: v-prla/moq
 /// <summary>
 /// Throws <see cref="StrictMockException"/>.
 /// </summary>
 public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next) => throw new StrictMockException();
コード例 #29
0
 public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext) => null;
コード例 #30
0
ファイル: MockBehavior.cs プロジェクト: steffenloesch/moq
 /// <summary>
 /// Executes the delegate received in the constructor.
 /// </summary>
 public IMethodReturn Execute(IMethodInvocation invocation, GetNextBehavior next) => behavior(invocation, next);
コード例 #31
0
ファイル: EventBehavior.cs プロジェクト: ajaishankar/moq
        /// <inheritdoc />
        public IMethodReturn Invoke(IMethodInvocation invocation, GetNextBehavior getNext)
        {
            var isEventAddOrRemove = invocation.MethodBase.IsSpecialName &&
                                     (invocation.MethodBase.Name.StartsWith("add_") || invocation.MethodBase.Name.StartsWith("remove_"));

            if (!isEventAddOrRemove)
            {
                return(getNext()(invocation, getNext));
            }

            var info = invocation.MethodBase.DeclaringType.GetRuntimeEvent(
                invocation.MethodBase.Name.Replace("add_", string.Empty).Replace("remove_", string.Empty));

            if (info != null)
            {
                EventRaiser raiser = null;
                if ((raiser = CallContext <EventRaiser> .GetData()) != null)
                {
                    try
                    {
                        var mock = ((IMocked)invocation.Target).Mock;
                        if (mock.State.TryGetValue <Delegate>(info.Name, out var handler) &&
                            handler != null)
                        {
                            switch (raiser)
                            {
                            case EmptyEventRaiser _:
                                handler.DynamicInvoke(invocation.Target, EventArgs.Empty);
                                break;

                            case EventArgsEventRaiser a:
                                handler.DynamicInvoke(invocation.Target, a.EventArgs);
                                break;

                            case CustomEventRaiser c:
                                handler.DynamicInvoke(c.Arguments);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    finally
                    {
                        CallContext <EventRaiser> .SetData(null);
                    }
                }
                else
                {
                    var handler = invocation.Arguments.FirstOrDefault() as Delegate;
                    if (handler != null)
                    {
                        var mock = ((IMocked)invocation.Target).Mock;
                        if (invocation.MethodBase.Name.StartsWith("add_"))
                        {
                            CombineDelegate(info, handler, mock);
                        }
                        else
                        {
                            RemoveDelegate(info, handler, mock);
                        }
                    }
                }
            }

            return(getNext()(invocation, getNext));
        }