public static class Mockery
{
private static readonly object [] SingleNull = new object[1];
public static T GenerateMock<T>(params object[] argumentsForConstructor)
where T : class
{
return
MockRepository.GenerateMock<T>(argumentsForConstructor ?? SingleNull);
}
/* other stuff */
}
Drop the class in your project and then replace MockRepository with
Mockery in your tests. It should pass.
public class Foo
{
public Foo(object [] o)
{
Console.WriteLine(o??(object)"null array");
}
public static void Main(string[] args)
{
Mockery.GenerateMock<Foo>(null);
}
}
output: null array
2009/7/22 Krzysztof Koźmic (2) <krzy...@kozmic.pl>:
> That's just drawback of using params object[] because this means:
> "literally anything". That's why we deprecated this in DynamicProxy
Krzysztof,
I'm curious to know what is the replacement for this.
Cheers,
Kenneth
Just to clarify that my workaround is just for that specific use case.
There is no reason to pass in a single null to GenerateMock other then
pass it down to the constructor. It is not intended for a general
solution to params object[].
> Say you have a ctor like this: Foo.ctor(IBar[] bars); and you want to
> pass empty array of IBar
Well, you can still workaround it in the GenerateMock use case. I
think it has no meaning of passing an IBar array other then giving it
to the constructor.
public static T GenerateMock<T>(params object[] argumentsForConstructor)
where T : class
{
if (argumentsForConstructor == null)
{
argumentsForConstructor = SingleNull;
}
else if
(argumentsForConstructor.GetType().GetElementType() != typeof(object))
{
argumentsForConstructor = new object[]{argumentsForConstructor};
}
return MockRepository.GenerateMock<T>(argumentsForConstructor);
}
> if you call Mockery.GenerateMock<Foo>(new IBar[]{}); it won't work.
> because arrays in .NET are covariant and CLR will treat this as if you
> passed empty array of objects as your params array, which would
> indicate you want to call the default constructor, which is not what
> you want in this case. You'd have to pass it explicitly as new object[]
> {new IBar[]{}} which is inconsistent with the other cases and
> confusing.
This made me recall the longer discussion on this topic when Java 1.5
was released. Yes, I agree there are confusions by the design of using
object array for variable parameters. But I believe, IMHO, those
workaround helps to reduce the confusions brought by variable
parameter and gives less surprise to API users.
If you don't mind, I'm still curious about the alternative in DP 2.2 :)
Thanks,
Kenneth