Exemplo n.º 1
0
        public void MethodCallCtorWontAcceptNullArgs()
        {
            MethodInfo method = typeof(string)
                                .GetMethod("StartsWith", new Type[] { typeof(string) });

            Assert.Throws <ArgumentNullException>(
                () => MethodFormatter.ToString(null, method, null, null));
        }
Exemplo n.º 2
0
        public void MethodCallWithArgumentsMissing()
        {
            MethodInfo method = typeof(string)
                                .GetMethod("StartsWith", new Type[] { typeof(string) });

            Assert.Equal(
                "String.StartsWith(missing parameter);",
                MethodFormatter.ToString(null, method, new object[0]));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns a <see cref="String"/> representation of the specified <paramref name="method"/>
        /// that is fully qualified (not including <see cref="Assembly.FullName"/>) and contains all
        /// generic and regular parameters, if they exist.
        /// </summary>
        /// <param name="method">The method to return a <see cref="String"/> representation of.</param>
        /// <returns>
        /// </returns>
        /// A <see cref="String"/> representation of the specified <paramref name="method"/>
        /// that is fully qualified (not including <see cref="Assembly.FullName"/>) and contains all
        /// generic and regular parameters, if they exist.
        /// <exception cref="System.ArgumentNullException">method</exception>
        public static string GetFullNameWithSignature(this MethodInfo method)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            var methodFormatter = new MethodFormatter(method);

            return(methodFormatter.ToString());
        }
        /// <summary>
        /// Logs the unexpected method call
        /// </summary>
        /// <param name="invocation"></param>
        /// <param name="message"></param>
        public void LogUnexpectedMethodCall(IInvocation invocation, string message)
        {
            var method = MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments);

            Debug.WriteLine(string.Format("{0}: {1}", method, message));

            if (AlternativeWriter != null)
            {
                AlternativeWriter.WriteLine(string.Format("{0}: {1}", method, message));
            }

            WriteStackTrace();
        }
        /// <summary>
        /// Logs the given method and arguments
        /// that was used to create an expectation
        /// </summary>
        /// <param name="invocation"></param>
        public void LogExpectation(IInvocation invocation)
        {
            var method = MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments);

            Debug.WriteLine(string.Format("Expectation: {0}", method));

            if (AlternativeWriter != null)
            {
                AlternativeWriter.WriteLine(string.Format("Expectation: {0}", method));
            }

            WriteStackTrace();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Logs the unexpected method call
        /// </summary>
        /// <param name="invocation"></param>
        /// <param name="message"></param>
        public void LogUnexpectedMethodCall(IInvocation invocation, string message)
        {
            var method = MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments);

            Trace.WriteLine(string.Format("{0}: {1}", method, message));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Logs the expected method call
        /// </summary>
        /// <param name="invocation"></param>
        public void LogExpectedMethodCall(IInvocation invocation)
        {
            var method = MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments);

            Trace.WriteLine(string.Format("Method Call: {0}", method));
        }
Exemplo n.º 8
0
 /// <summary>
 /// Returns the string representation of the expectation
 /// </summary>
 /// <returns>string</returns>
 public override string GetDisplayName(IInvocation invocation)
 {
     return(MethodFormatter.ToString(invocation, MethodGet, Arguments,
                                     (x, i) => Arguments[i].Message));
 }
Exemplo n.º 9
0
        /// <summary>
        /// Verifies expectations have been met for the given mocked object.
        /// When strictly is "true" then methods called without an expectation will fail verification
        /// </summary>
        /// <typeparam name="T">the mocked type</typeparam>
        /// <param name="instance">the mocked instance to verify</param>
        /// <param name="strictly">"true" for strict verification, otherwise normal verification</param>
        /// <exception cref="Rhino.Mocks.Exceptions.ExpectationViolationException">
        /// thrown when expectations have not been met or (in the case of strict verification)
        /// if a method was called that was not setup with an expectation
        /// </exception>
        /// <exception cref="System.ArgumentNullException">thrown when the instance is null</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">thrown when the instance cannot be identified as a mocked object</exception>
        public static void VerifyExpectations <T>(this T instance, bool strictly)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance", "Verification cannot be performed on a null object or instance.");
            }

            var invocation = instance as IInvocation;
            var container  = GetExpectationContainer(instance);

            if (container == null)
            {
                throw new ArgumentOutOfRangeException("instance", "Verification can only be performed on a mocked object or instance.");
            }

            var actuals      = container.ListActuals();
            var expectations = container.ListExpectations();

            if (expectations.Length == 0 && actuals.Length == 0)
            {
                return;
            }

            var unmet = expectations
                        .Where(x => !x.ExpectationMet)
                        .ToArray();

            if (!unmet.Any() && !strictly)
            {
                return;
            }

            var buffer = new StringBuilder();

            if (strictly)
            {
                for (int actualIndex = 0; actualIndex < actuals.Length; actualIndex++)
                {
                    var foundActual = false;
                    var actual      = actuals[actualIndex];
                    for (int expectationIndex = 0; expectationIndex < expectations.Length; expectationIndex++)
                    {
                        var expectation = expectations[expectationIndex];
                        if (expectation.HandledActual(actual))
                        {
                            foundActual = true;
                            break;
                        }
                    }

                    if (foundActual)
                    {
                        continue;
                    }

                    var methodName = MethodFormatter.ToString(invocation, actual.Method, actual.Arguments);
                    buffer.Append(methodName)
                    .Append(" Expected #0, Actual #1.")
                    .AppendLine();
                }
            }

            for (int index = 0; index < unmet.Length; index++)
            {
                var item       = unmet[index];
                var methodName = item.GetDisplayName(invocation);

                buffer.Append(methodName)
                .AppendFormat(" Expected #{0}, Actual #{1}.", item.ExpectedCount, item.ActualCount)
                .AppendLine();
            }

            if (buffer.Length == 0)
            {
                return;
            }

            var message = buffer
                          .Remove(buffer.Length - 2, 2)
                          .ToString();

            throw new ExpectationViolationException(message);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Logs the given method and arguments
        /// that was used to create an expectation
        /// </summary>
        /// <param name="invocation"></param>
        public void LogExpectation(IInvocation invocation)
        {
            var method = MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments);

            writer.WriteLine(string.Format("Expectation: {0}", method));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Handles an unexpected method call
        /// </summary>
        /// <param name="invocation"></param>
        /// <param name="method"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public object HandleUnexpectedMethodCall(IInvocation invocation, MethodInfo method, object[] arguments)
        {
            if (UnexpectedCallBehavior == UnexpectedCallBehaviors.BaseOrDefault || UnexpectedCallBehavior == UnexpectedCallBehaviors.BaseOrThrow)
            {
                if (IsPartialInstance && !method.IsAbstract)
                {
                    RhinoMocks.Logger.LogUnexpectedMethodCall(invocation,
                                                              "Partial: Calling original method.");

                    invocation.Proceed();
                    return(invocation.ReturnValue);
                }
            }

            if (UnexpectedCallBehavior == UnexpectedCallBehaviors.BaseOrThrow)
            {
                RhinoMocks.Logger.LogUnexpectedMethodCall(invocation,
                                                          "Mock: No expectation or stub created, no base method found and throw requested.");

                throw new Rhino.Mocks.Exceptions.ExpectationViolationException("No expectation or stub found for " + MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments));
            }

            if (UnexpectedCallBehavior == UnexpectedCallBehaviors.Throw)
            {
                RhinoMocks.Logger.LogUnexpectedMethodCall(invocation,
                                                          "Mock: No expectation or stub created and throw requested.");

                throw new Rhino.Mocks.Exceptions.ExpectationViolationException("No expectation or stub found for " + MethodFormatter.ToString(invocation, invocation.Method, invocation.Arguments));
            }

            if (method.IsSpecialName)
            {
                var methodName = method.Name;
                if (methodName.StartsWith("get_", StringComparison.Ordinal) ||
                    methodName.StartsWith("set_", StringComparison.Ordinal))
                {
                    RhinoMocks.Logger.LogUnexpectedMethodCall(invocation,
                                                              "Property: Dynamic handling of property.");

                    var propertyKey = GeneratePropertyKey(method, arguments);
                    if (expectedProperties.ContainsKey(propertyKey))
                    {
                        expectedProperties.Remove(propertyKey);
                    }


                    if (methodName.StartsWith("get_", StringComparison.Ordinal))
                    {
                        if (dynamicProperties.ContainsKey(propertyKey))
                        {
                            return(dynamicProperties[propertyKey]);
                        }
                    }
                    else if (methodName.StartsWith("set_", StringComparison.Ordinal))
                    {
                        dynamicProperties[propertyKey] = arguments.Last();
                        return(null);
                    }
                }

                if (methodName.StartsWith("add_", StringComparison.Ordinal) ||
                    methodName.StartsWith("remove_", StringComparison.Ordinal))
                {
                    RhinoMocks.Logger.LogUnexpectedMethodCall(invocation,
                                                              "Event: Dynamic handling of event.");

                    var subscription = (Delegate)arguments[0];
                    HandleEventSubscription(method, subscription);
                }
            }

            if (!method.IsSpecialName)
            {
                RhinoMocks.Logger.LogUnexpectedMethodCall(invocation,
                                                          "Mock: No expectation or stub created.");
            }

            return(GetDefaultValue(method.ReturnType));
        }
Exemplo n.º 12
0
 public void MethodCallCtorWontAcceptNullMethod()
 {
     Assert.Throws <ArgumentNullException>(
         () => MethodFormatter.ToString(null, null));
 }
Exemplo n.º 13
0
        public void MethodCallToStringWithSeveralArguments()
        {
            string actual = MethodFormatter.ToString(null, GetMethodInfo("IndexOf", "abcd", 4), new object[] { "abcd", 4 });

            Assert.Equal("String.IndexOf(\"abcd\", 4);", actual);
        }
Exemplo n.º 14
0
        public void MethodCallToString()
        {
            string actual = MethodFormatter.ToString(null, GetMethodInfo("StartsWith", ""), new object[] { "abcd" });

            Assert.Equal("String.StartsWith(\"abcd\");", actual);
        }