Monday, August 8, 2016

Could not find a parameterless constructor when using Moq

If you need to Mock objects which expect parameters in the constructor, you may encounter a message such as the following:

"Can not instantiate proxy of class: DataAccess.DataModel.MyDbContext. Could not find a parameterless constructor."

Based on the error message, the solution requires you to pass a constructor to the parameter of your Mocked object.

So how exactly do you do that?

Well, the solution is, in fact, rather easy!

You just pass the required parameter to your Mocked object like so:


In this case, I am passing the database connectionString as a parameter to my Mocked DbContext object so that it can instantiate the object appropriately. That is all there is to it!

No comments:

Post a Comment