【问题标题】:Moq internal class and/or internal methodMoq 内部类和/或内部方法
【发布时间】:2021-04-07 22:56:51
【问题描述】:

在我的项目中,我设置:

[assembly: InternalsVisibleTo("xyz")]

当我的类和方法公开时,我的单元测试工作。

public class MainController
{
    public virtual void RunForm()
    {
        ...
    }

如果我更改为内部,我的单元测试将失败。这是起订量的限制吗?

var logger = new Mock<IExceptionLogger>();
var name = new Mock<MainController>
{
    CallBase = true
};
name.Setup(x => x.RunForm()).Throws(new Exception()));
name.Object.Init(logger.Object);
logger.Verify(m => m.LogError(It.IsAny<Exception>(), Times.Once);

例外:

Test method Tests.Controllers.MainControllerTest.ExceptionsInitGetLoggedToAppInsights threw exception: 
    System.ArgumentException: Cannot set up MainController.RunForm because it is not accessible to the proxy generator used by Moq:
    Can not create proxy for method Void RunForm() because it or its declaring type is not accessible. Make it public, or internal and mark your assembly with [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute, because assembly Abc is not strong-named.

【问题讨论】:

  • 它应该可以工作,但是您可以在 .csproj 文件中设置设置而不是汇编指令:meziantou.net/declaring-internalsvisibleto-in-the-csproj.htm
  • mark your assembly with [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute
  • @silkfire 嗯,结果与此相同
  • @devNull 请作为答案发布,我会接受。我在几个地方看到了这一点并想,这只是意味着我必须将我的程序集放入字符串中。我不知道除了我自己的程序集之外我还需要它。
  • 您能提供您的 {project}/Properties/AssemblyInfo.cs 文件吗?

标签: c# moq .net-4.6.1


【解决方案1】:

如错误消息中所述,您实际上需要将[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] 属性添加到您的程序集中。 DynamicProxyGenAssembly2 是 Moq 在内部用于创建类的代理实例以覆盖/实现虚拟/接口方法的程序集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多