Exemple #1
0
		/// <summary>
		/// Invokes this object. The event is fired on the receiver of the invocation.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			if (invocation == null) 
				throw new ArgumentNullException("invocation");

			((IMockObject) invocation.Receiver).RaiseEvent(eventName, eventArgs);
		}
Exemple #2
0
		protected bool ShouldCallInvokeImplementation(Invocation invocation)
		{
			/* ^ */ var _typeInfo = this.MockedTypes.PrimaryType.GetTypeInfo(); /* [email protected] ^ */

			// Only transparent mocks of classes can have their implemenation invoked
			if (/* ^ */ MockStyle == MockStyle.Transparent && !_typeInfo.IsInterface /* [email protected] ^ */)
			{
				// Events can go through because invoking them is different than their binding
				// (and because that is kind of how I think it should work...but technically invoking them maybe shouldn't in a transparent mock.)
				// The implementation should only be invoked if no expectations
				// have been set for this method
				if (invocation.IsEventAccessor || !MockFactory.HasExpectationFor(invocation))
				{
					// As classes and interfaces can be combined into a single mock, we have
					// to be sure that the target method actually belongs to a class
					if (
						MockedTypes.PrimaryType == invocation.Method.DeclaringType
						//|| MockedTypes.PrimaryType.IsSubclassOf(invocationForMock.Method.DeclaringType)
						|| invocation.Method.DeclaringType.IsAssignableFrom(MockedTypes.PrimaryType)
						//invocationForMock.Method.DeclaringType.IsInterface
						)
					{
						return true;
					}
				}
			}

			return false;
		}
Exemple #3
0
		/// <summary>
		/// Invokes this object.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			if (invocation == null) 
				throw new ArgumentNullException("invocation");

			invocation.Result = evaluate();
		}
		/// <summary>
		/// Performs the specified invocation on the corresponding expectation if a match was found.
		/// </summary>
		/// <param name="invocation">The invocation to match.</param>
		public override bool Perform(Invocation invocation)
		{
			//loop through all active expectations looking for a match
			foreach (var expectation in this)
			{
				if (expectation.Matches(invocation)) //expectation.IsValid && 
				{
					return expectation.Perform(invocation);
				}
			}

			//loop through through all inactive expectations looking for a match
			foreach (var expectation in this)
			{
				if(expectation.MatchesIgnoringIsActive(invocation))
				{
					//var ordered = expectation as OrderedExpectationList;
					//if (ordered != null)
					//{
					//    ordered.PerformAgainstInactive(invocation);
					//    return false;
					//}
					
					var buildable = expectation as BuildableExpectation;
					if (buildable != null)
					{
						buildable.IncreaseCallCount();
						return false;
					}
				}
			}

			return false;
		}
		void IAction.Invoke(Invocation invocation)
		{
			if(invocation.IsPropertyGetAccessor)
			{
				using(new PropertyStorageMarker())
				{
					invocation.InvokeOn(_mockObject);
				}
			}
		}
		public void Intercept(IInvocation invocation)
		{
			if(InvocationRecorder.Recording)
			{
				InvocationRecorder.Current.Invocation = new Invocation(invocation.Method, invocation.Arguments);
				return;
			}

			// Check for calls to basic NMock infrastructure
			if (MockObjectMethods.ContainsKey(invocation.Method))
			{
				try
				{
					invocation.ReturnValue = invocation.Method.Invoke(this, invocation.Arguments);
				}
				catch (TargetInvocationException tie)
				{
#if !SILVERLIGHT
					// replace stack trace with original stack trace
					FieldInfo remoteStackTraceString = typeof (Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
					remoteStackTraceString.SetValue(tie.InnerException, tie.InnerException.StackTrace + Environment.NewLine);

					throw tie.InnerException;
#else
					throw;
#endif
				}

				return;
			}

			// Ok, this call is targeting a member of the mocked class
			object invocationTarget;
			if (MockedTypes.PrimaryType == invocation.Method.DeclaringType && invocation.InvocationTarget != null)
			{
				invocationTarget = invocation.InvocationTarget;
			}
			else
			{
				invocationTarget = invocation.Proxy;
			}

			var invocationForMock = new Invocation(invocationTarget, invocation.Method, invocation.Arguments);

			if (ShouldCallInvokeImplementation(invocationForMock))
			{
				invocation.Proceed();

				if (!MockFactory.HasExpectationFor(invocationForMock))
					return;
			}

			invocation.ReturnValue = ProcessCallAgainstExpectations(invocationForMock);
		}
		/// <summary>
		/// Invokes this object. Sets the value of the parameter with the specified name of the invocation.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			ParameterInfo[] paramsInfo = invocation.MethodParameters;

			for (int i = 0; i < paramsInfo.Length; i++)
			{
				if (paramsInfo[i].Name == name)
				{
					invocation.Parameters[i] = value;
					return;
				}
			}

			throw new ArgumentException("no such parameter", name);
		}
Exemple #8
0
		protected object ProcessCallAgainstExpectations(Invocation invocation)
		{
			if (PropertyStorageMarker.UsePropertyStorage)
			{
				var interceptedValues = ((IMockObject)invocation.Receiver).InterceptedValues;
				if (interceptedValues.ContainsKey(invocation.MethodSignatureForSetter))
				{
					return interceptedValues[invocation.MethodSignatureForSetter];
				}
			}

			((IInvokable)this).Invoke(invocation);

			if (invocation.IsThrowing)
			{
				throw invocation.Exception;
			}

			if (invocation.Result == Missing.Value && invocation.Method.ReturnType != typeof(void))
			{
				//var exception = new UnexpectedInvocationException(invocation,"No matching expectation was found for this invocation.  " + invocation);

				//MockFactory.OrderingException = exception;

				//throw exception;
			}

			if (invocation.IsPropertySetAccessor)
			{
				var interceptedValues = ((IMockObject)invocation.Receiver).InterceptedValues;

				if (interceptedValues.ContainsKey(invocation.MethodSignature))
					interceptedValues[invocation.MethodSignature] = invocation.SetterResult;
				else
					interceptedValues.Add(invocation.MethodSignature, invocation.SetterResult);
			}

			return invocation.Result;
		}
Exemple #9
0
		/// <summary>
		/// Invokes this object.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			Type returnType = invocation.MethodReturnType;

			/* ^ */ var _returnType = returnType.GetTypeInfo(); /* [email protected] ^ */

			if (returnType == typeof(void))
			{
				return; // sanity check
			}

			lock (_lock)
			{
				if (_results.ContainsKey(returnType))
				{
					var action = _results[returnType];
					action.Invoke(invocation);
				}
				else if (returnType.IsArray)
				{
					invocation.Result = NewEmptyArray(returnType);
				}
				else if (/* ^ */ _returnType.IsValueType /* [email protected] ^ */)
				{
					invocation.Result = Activator.CreateInstance(returnType);
				}
				else if (defaultResults.ContainsKey(returnType))
				{
					var action = defaultResults[returnType];
					action.Invoke(invocation);
				}
				else
				{
					throw new InvalidOperationException("No action registered for return type " + returnType);
				}
			}
		}
Exemple #10
0
		public override bool ContainsOrderedExpectationFor(Invocation invocation)
		{
			for (int i = current; i < Count; i++)
			{
				if (this[i] as IExpectationList != null)
				{
					return ((IExpectationList)this[i]).ContainsOrderedExpectationFor(invocation);
				}
				if (this[i].Matches(invocation))
				{
					return true;
				}
			}
			return false;
		}
Exemple #11
0
		public override bool Perform(Invocation invocation)
		{
			if (Count == 0)
				return false;

			//you would think it would be "if (CurrentExpectation.HasBeenMet)" but "atleast" matchers will have been met
			//when they can consume more, so increment after a match check
			//if (CurrentExpectation.HasBeenMet)
			if (!CurrentExpectation.Matches(invocation) && !invocation.MockObject.IgnoreUnexpectedInvocations)
				current++;

			//now if this one doesn't match then this is unexpected
			if (CurrentExpectation.Matches(invocation))
			{
				var result = CurrentExpectation.Perform(invocation);

				//this helps for adding breakpoints and troubleshooting when returning false
				if (result)
					return true;
				else
					return false;
			}

			return false;
		}
Exemple #12
0
		public override bool MatchesIgnoringIsActive(Invocation invocation)
		{
			if (CurrentExpectation == null)
				return false;

			if (Count == 0)
				return false;

			return (CurrentExpectation.MatchesIgnoringIsActive(invocation)
				|| (CurrentExpectation.HasBeenMet
				&& NextExpectationMatchesIgnoringIsActive(invocation))); //look ahead at the next if the current is an "atleast" matcher
		}
		/// <summary>
		/// Invokes this object. Sets the parameter at the specified index of the invocation to the specified value.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			invocation.Parameters[index] = value;
		}
Exemple #14
0
		/// <summary>
		/// Invokes this object.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			collectedArgumentValue = invocation.Parameters[argumentIndex];
		}
		private bool ExtraMatchersMatch(Invocation invocation)
		{
			return _extraMatchers.All(matcher => matcher.Matches(invocation));
		}
Exemple #16
0
		/// <summary>
		/// Invokes this object.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			if (handler != null)
				handler.Invoke(invocation.Parameters);
		}
		/// <summary>
		/// Checks whether stored expectations matches the specified invocation.
		/// </summary>
		/// <param name="invocation">The invocation to check.</param>
		/// <returns>Returns whether one of the stored expectations has met the specified invocation.</returns>
		public override bool Matches(Invocation invocation)
		{
			var matchFound = this.Any(expectation => expectation.Matches(invocation));
			return matchFound;
		}
Exemple #18
0
		public void ProcessEventHandlers(Invocation invocation)
		{
			var handler = invocation.Parameters[0] as Delegate;
			var name = invocation.MethodName;

			if (name.StartsWith(Constants.ADD))
			{
				AddEventHandler(name.Substring(Constants.ADD.Length), handler);
			}
			else if (name.StartsWith(Constants.REMOVE))
			{
				RemoveEventHandler(name.Substring(Constants.REMOVE.Length), handler);
			}
		}
Exemple #19
0
		private bool MatchesArgumentValues(Invocation invocation)
		{
			ParameterInfo[] paramsInfo = invocation.MethodParameters;

			for (int i = 0; i < invocation.Parameters.Count; i++)
			{
				object value = paramsInfo[i].IsOut ? OutParameter : invocation.Parameters[i];

				if (!valueMatchers[i].Matches(value))
				{
					return false;
				}
			}

			return true;
		}
Exemple #20
0
		private bool MatchesArguments(Invocation invocation)
		{
			return invocation.Parameters.Count == valueMatchers.Count
				   && MatchesArgumentValues(invocation);
		}
		public override bool MatchesIgnoringIsActive(Invocation invocation)
		{
			return this.Any(e => e.MatchesIgnoringIsActive(invocation));
		}
Exemple #22
0
		private bool NextExpectationMatches(Invocation invocation)
		{
			if (HasNextExpectation)
			{
				//this helps skip over empty ordered expectations
				if (NextExpectation.IsValid && !NextExpectation.IsActive && NextExpectation.HasBeenMet)
				{
					current++;
					return NextExpectationMatches(invocation);
				}

				return NextExpectation.Matches(invocation);
			}

			return false;
		}
Exemple #23
0
		private bool NextExpectationMatchesIgnoringIsActive(Invocation invocation)
		{
			return HasNextExpectation && NextExpectation.MatchesIgnoringIsActive(invocation);
		}
		private static void ProcessEventHandlers(Invocation invocation)
		{
			if (invocation.IsEventAccessor)
			{
				var mockObject = invocation.Receiver as IMockObject;
				if (mockObject != null)
				{
					mockObject.ProcessEventHandlers(invocation);
				}
			}
		}
Exemple #25
0
		void IAction.Invoke(Invocation invocation)
		{
			invocation.SetterResult = invocation.Arguments[invocation.Arguments.Length - 1];
		}
		public override bool ContainsOrderedExpectationFor(Invocation invocation)
		{
			foreach (var expectation in this)
			{
				if (expectation as IExpectationList != null)
				{
					return ((IExpectationList)expectation).ContainsOrderedExpectationFor(invocation);
				}

				if (expectation.Matches(invocation))
				{
					return true;
				}
			}
			return false;
		}
Exemple #27
0
		/// <summary>
		/// Gets the default result for an invocation.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		/// <returns>The default value to return as result of the invocation. 
		/// <see cref="Missing.Value"/> if no default value was provided.</returns>
		private object GetStubResult(Invocation invocation)
		{
			Type returnType = invocation.MethodReturnType;
			/* ^ */ var _returnTypeInfo = returnType.GetTypeInfo(); /* [email protected] ^ */

			// void method
			if (returnType == typeof(void))
			{
				return Missing.Value;
			}

			// see if developer provides a return value
			object returnValue = MockFactory.ResolveType(invocation.Receiver, returnType);

			if (returnValue != Missing.Value)
			{
				return returnValue;
			}

			if (/* ^ */ _returnTypeInfo.IsValueType /* [email protected] ^ */)
			{
				// use default contructor for value types
				return Activator.CreateInstance(returnType);
			}

			if (returnType == typeof(string))
			{
				// string empty for strings
				return string.Empty;
			}

			if (/* ^ */ _returnTypeInfo.IsClass && _returnTypeInfo.ImplementedInterfaces.Any(t => t == typeof(IEnumerable)) /* [email protected] ^ */)
			{
				// for enumerables (List, Dictionary) we create an empty object
				return Activator.CreateInstance(returnType);
			}

			if (/* ^ */ _returnTypeInfo.IsSealed /* [email protected] ^ */)
			{
				// null for sealed classes
				return null;
			}

			// a mock for interfaces and all cases no covered above
			return MockFactory.NewMock(returnType, GetMemberName(invocation), MockFactory.GetDependencyMockStyle(invocation.Receiver, returnType) ?? MockStyle);
		}
Exemple #28
0
		/// <summary>
		/// Invokes this object. Sets the exception the invocation will throw.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			invocation.Exception = exception;
		}
Exemple #29
0
		/// <summary>
		/// Invokes this object by signaling the event.
		/// </summary>
		/// <param name="invocation">The invocation.</param>
		void IAction.Invoke(Invocation invocation)
		{
			signal.Set();
		}
Exemple #30
0
		void IInvokable.Invoke(Invocation invocation)
		{
			switch (MockStyle)
			{
				case MockStyle.Default:
				case MockStyle.Transparent:
					try
					{
						//call up the the factory to route this invocation
						MockFactory.Dispatch(invocation);
					}
					catch (UnexpectedInvocationException)
					{
						if (IgnoreUnexpectedInvocations)
						{
							//clear the factory expectation
							MockFactory.ClearException();
						}
						else
						{
							throw;
						}
					}
					break;

				case MockStyle.Stub:
					{
						if (MockFactory.HasExpectationForIgnoringIsActive(invocation))
						{
							goto case MockStyle.Default;
						}

						// check whether we already have a value for this call
						object result;

						if (invocation.IsPropertySetAccessor)// remember values set in a property setter
						{
							if (assignedPropertyResults.ContainsKey(invocation.MethodName)) //TODO: stubs don't support indexers! need Item[int] or Item[string,int]
							{
								assignedPropertyResults[invocation.MethodName] = invocation.Parameters[0];
							}
							else
							{
								assignedPropertyResults.Add(invocation.MethodName, invocation.Parameters[0]);
							}

							return;
						}
						else if (invocation.IsEventAccessor)
						{
							ProcessEventHandlers(invocation);
							return;
						}
						else if (invocation.IsPropertyGetAccessor && assignedPropertyResults.ContainsKey(invocation.MethodName))
						{
							result = assignedPropertyResults[invocation.MethodName];
						}
						else if (rememberedMethodResults.ContainsKey(invocation.Method))
						{
							result = rememberedMethodResults[invocation.Method];
						}
						else
						{
							result = GetStubResult(invocation);
							rememberedMethodResults.Add(invocation.Method, result);
						}

						if (result != Missing.Value)
						{
							invocation.Result = result;
						}

						break;
					}
				case MockStyle.RecursiveStub:
					{
						if (MockFactory.HasExpectationFor(invocation))
						{
							goto case MockStyle.Default;
						}

						object result;
						if (rememberedResults.ContainsKey(invocation.MethodName))
						{
							result = rememberedResults[invocation.MethodName];
						}
						else
						{
							result = GetStubResult(invocation);
							rememberedResults.Add(invocation.MethodName, result);
						}

						if (result != Missing.Value)
						{
							invocation.Result = result;
						}

						break;
					}
			}
		}