NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Add overload for Call.ToString()

Open jgauffin opened this issue 11 years ago • 4 comments

It would be nice if Call.ToString() could print out as the call would look like. i.e. something like:

        foreach (var call in groupReps.ReceivedCalls())
        {
            Console.WriteLine();
        }

Would print

SomeProxy.DoThis(5, Hello)

jgauffin avatar Aug 24 '12 07:08 jgauffin

That's a very nice idea. Any chance you could try and spike out an implementation?

dtchepak avatar Aug 24 '12 07:08 dtchepak

Here is a quick and dirty solution which I currently use:

    public static string FormatCall(this ICall call)
    {
        return string.Format("{0}.{1}({2})", call.Target().GetType().Name,
                             call.GetMethodInfo().Name,
                             FormatArguments(call));
    }

    public static string FormatArguments(this ICall call)
    {
        var values = call.GetArguments();
        var parameters = call.GetMethodInfo().GetParameters();

        var result = new string[values.Length];
        for (var i = 0; i < parameters.Length; i++)
        {
            var parameter = parameters[i];
            var value = values[i];

            // not very SOLID ;)
            if (value is string)
            {
                result[i] = string.Format(@"{0} = ""{1}""", parameter.Name, value);
            }
            else if (value.GetType().IsArray)
            {
                result[i] = string.Format(@"{0} = [{1}]", parameter.Name, string.Join(", ", value));
            }
            else if (value is IEnumerable)
            {
                result[i] = string.Format(@"{0} = []{{{1}}}", parameter.Name, string.Join(", ", value));
            }
            else
            {
                result[i] = string.Format("{0} = {1}", parameter.Name, value);
            }
        }

        return string.Join(", ", result);
    }

jgauffin avatar Aug 24 '12 07:08 jgauffin

@dtchepak Do you have a method that can fetch the call's paramters in case they are an array? `else if (value.GetType().IsArray)

        {

            result[i] = string.Format(@"{0} = [{1}]", parameter.Name, string.Join(", ", value));

        }`

And the call itself: _car.StoreLuggage(new[] {new DateTime(2001, 01, 01), new DateTime(2002, 02, 02)};)

This code will break since the parameter is array of datetime. String join won't handle it.

DennisNerush avatar Jan 21 '17 00:01 DennisNerush

Hi @DennisNerush, Can you use Array.ConvertAll or .Select to map everything to strings first?

dtchepak avatar Jan 21 '17 22:01 dtchepak