48

How to call the constructor with interface arguments when you are mocking a conc...

 2 years ago
source link: https://www.codesd.com/item/how-to-call-the-constructor-with-interface-arguments-when-you-are-mocking-a-concrete-class-with-moq.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to call the constructor with interface arguments when you are mocking a concrete class with Moq

advertisements

I have the following class, which uses constructor injection:

public class Service : IService
{
    public Service(IRepository repository, IProvider provider) { ... }
}

For most methods in this class, I simply create Moq mocks for IRepository and IProvider and construct the Service. However, there is one method in the class that calls several other methods in the same class. For testing this method, instead of testing all those methods together, I want to test that the method calls those methods correctly and processes their return values correctly.

The best way to do this is to mock Service. I've mocked concrete classes with Moq before without issue. I've even mocked concrete classes that require constructor arguments with Moq without issue. However, this is the first time I've needed to pass mocked arguments into the constructor for a mocked object. Naturally, I tried to do it this way:

var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();

var service = new Mock<Service>(repository.Object, provider.Object);

However, that does not work. Instead, I get the following error:

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: My.Namespace.Service.
Could not find a constructor that would match given arguments:
    Castle.Proxies.IRepository
    Castle.Proxies.IProvider

This works fine if Service's constructor takes simple arguments like ints and strings, but not if it takes interfaces that I'm mocking. How do you do this?


I had a very similar problem when my equivalent of Service had an internal constructor, so it was not visible to Moq.

I added

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

to my AssemblyInfo.cs file for the implementing project. Not sure if it is relevant, but I wanted to add a suggestion on the off chance that it helps you or someone else.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK