在我的项目中,我设置了:
[assembly: InternalsVisibleTo("xyz")]
Run Code Online (Sandbox Code Playgroud)
当我的类和方法是公开的时,我的单元测试有效。
public class MainController
{
public virtual void RunForm()
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果我将其中任何一个更改为内部,我的单元测试都会失败。这是起订量的限制吗?
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);
Run Code Online (Sandbox Code Playgroud)
例外:
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.
Run Code Online (Sandbox Code Playgroud)
正如错误消息中所述,您实际上需要将该[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]属性添加到程序集中。DynamicProxyGenAssembly2是 Moq 在内部用于创建类的代理实例以覆盖/实现虚拟/接口方法的程序集。