【问题标题】:Moq Concrete Class with Internal Constructor具有内部构造函数的最小起订量具体类
【发布时间】:2017-08-18 14:43:14
【问题描述】:

我正在尝试最小化一个具有内部构造函数的具体类,即在MyAssembly 我有

public class MyClass {

    internal MyClass(){}

    // other methods including factory instance method
}

然后在 `TestAssembly' 的测试中我有

var mock = new Mock<MyClass>();

MyAssembly我已将以下内容添加到AssemblyInfo.cs

[assembly: InternalsVisibleTo("TestAssembly")]

但即使将TestAssembly 设置为MyAssembly 的朋友,Moq 仍然会抛出错误

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

Moq 应该能够以这种方式使用内部构造函数创建模拟吗?

【问题讨论】:

  • Moq 将无法访问构造函数来模拟实现。
  • @Nkosi 即使我将其标记为内部可见?我可以在我的测试项目中使用内部构造函数创建我的类的实例,那么为什么不能 Moq?
  • 看起来有人找到了答案。试试看。

标签: c# moq .net-assembly


【解决方案1】:

请参阅Advanced Features section of the Moq Quickstart

模拟另一个项目的内部类型:添加以下程序集 项目的属性(通常是 AssemblyInfo.cs)包含 内部类型:

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

【讨论】:

  • 很好的发现。我在快速开始时完全错过了这一点
  • 本以为这样可行,但现在收到错误 System.MethodAccessException Attempt by method 'Castle.Proxies.MyClassProxy..ctor(Castle.DynamicProxy.IInterceptor[])' to access method 'MyAssembly.MyClass..ctor()' failed. at Castle.Proxies.StageProxy..ctor(IInterceptor[] )
  • 使用 [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2")] 似乎有效
猜你喜欢
  • 1970-01-01
  • 2013-11-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多