moq/labs

Feature request: create mocks without requiring empty constructor/passing parameters

mcintyre321 opened this issue · 2 comments

Would it be possible to not throw exceptions when creating mocks of types with non-default parameters?

I know you can pass arguments, but it's not strongly typed to the constructor being called.

FakeItEasy doesn't require the arguments to be passed. I suspect it's using FormatterServices.GetUninitializedObject() under the hood, although I don't know if that's in .NET core.

I had a conversation about this many years ago on the mailing list where Krzysztof Koźmic said it wouldn't be possible with Castle at the time, but I did a proof of concept ProxyFactoryFactory back then and managed to create objects without running the ctor, so I think it can be done.

Steps to Reproduce

public class X  
{
    public X(string y){     }
} 

 new Moq.Mock<X>().Object.ToString(); // 

 
### Expected Behavior

The mock is created without throwing an exception. 

### Actual Behavior

throws "InvalidProxyConstructorArgumentsException:  Can not instantiate proxy of class: UserQuery+X.Could not find a parameterless constructor.

--


 

FakeItEasy doesn't require the arguments to be passed. I suspect it's using FormatterServices.GetUninitializedObject() under the hood, although I don't know if that's in .NET core.

Not exactly. We're actually examining the available constructors on the faked type. If there's a parameterless constructor, we try to make the proxy using it. If there isn't (or that fails) we go down the list of constructors, most parameters to least, and then attempt to resolve dummy values for each parameter. If we're successful, we attempt to create the proxy object using those parameters. If not, on to the next constructor.

Of course, this is mostly colour and doesn't get your feature implemented.

kzu commented

If you can't make it in (manual) code, you can't make it with Moq. That's unlikely to change, especially since the next version is switching to actual code generation at design or build time.