Moq Concrete Class with Internal Constructor

孤人 提交于 2019-12-11 06:27:24

问题


I'm attempting to Moq a concrete class that has an internal constructor, i.e., in MyAssembly I have

public class MyClass {

    internal MyClass(){}

    // other methods including factory instance method
}

then in my test in `TestAssembly' I have

var mock = new Mock<MyClass>();

in MyAssembly I have added the following to AssemblyInfo.cs

[assembly: InternalsVisibleTo("TestAssembly")]

but even setting TestAssembly to be a friend of MyAssembly, Moq still throws the error

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException
Can not instantiate proxy of class: Civica.Metadata.Models.Entities.Stage.
Could not find a parameterless constructor.

Should Moq be able to create mocks using internal constructors in this manner?


回答1:


See the Advanced Features section of the Moq Quickstart.

Mocking internal types of another project: add the following assembly attribute (typically to the AssemblyInfo.cs) to the project containing the internal types:

// This assembly is the default dynamic assembly generated Castle DynamicProxy, 
// used by Moq. Paste in a single line. 
[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]


来源:https://stackoverflow.com/questions/45759384/moq-concrete-class-with-internal-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!