Moq内部类和/或内部方法

3
在我的项目中,我设置了:
[assembly: InternalsVisibleTo("xyz")]

当我的类和方法是public时,我的单元测试可以正常工作。

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

如果我更改其中一个为internal,我的单元测试会失败。这是Moq的限制吗?
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文件中设置设置,而不是使用汇编指令:https://www.meziantou.net/declaring-internalsvisibleto-in-the-csproj.htm - silkfire
mark your assembly with [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] attribute - devNull
@silkfire 嗯,用那个结果一样 - Hoppe
@devNull请以答案的形式发布,我会接受。我在几个地方看到这样的说法,我以为只是要把我的程序集放在字符串中。我不知道还需要加上自己的程序集。 - Hoppe
你能提供你的 {project}/Properties/AssemblyInfo.cs 文件吗? - vladimir
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接