Moq 内部 class and/or 内部方法
Moq internal class and/or internal method
在我的项目中,我设置了:
[assembly: InternalsVisibleTo("xyz")]
当我的 class 和方法是 public 时,我的单元测试有效。
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.
如错误消息中所述,您实际上需要将 [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
属性添加到程序集中。 DynamicProxyGenAssembly2
是 Moq 在内部用于创建 class 到 override/implement virtual/interface 方法的代理实例的程序集。
在我的项目中,我设置了:
[assembly: InternalsVisibleTo("xyz")]
当我的 class 和方法是 public 时,我的单元测试有效。
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.
如错误消息中所述,您实际上需要将 [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
属性添加到程序集中。 DynamicProxyGenAssembly2
是 Moq 在内部用于创建 class 到 override/implement virtual/interface 方法的代理实例的程序集。