使用 moq 模拟静态属性 [英] Mock static property with moq
问题描述
我刚开始使用 moq.我正在为 HttpModule
创建一些单元测试用例,一切正常,直到我点击 static
属性,如下
I am pretty new to use moq. I am into creating some unit test case to HttpModule
and everything works fine until I hit a static
property as follows
this.applicationPath = (HttpRuntime.AppDomainAppVirtualPath.Length > 1) ? HttpRuntime.AppDomainAppVirtualPath : String.Empty;
我不知道如何为 static
类和类似 HttpRuntime.AppDomainAppVirtualPath
的属性创建模拟.context
、request
和 response
已经用我从 moq 得到的示例代码很好地模拟了.如果有人可以帮助我,我将不胜感激.
I do not know how create mocks for static
class and property like HttpRuntime.AppDomainAppVirtualPath
. The context
, request
and response
have been mocked well with sample code I get from moq. I will appreciate if somebody can help me on this.
推荐答案
Moq 不能伪造静态成员.
Moq can't fake static members.
作为一种解决方案,您可以创建一个包含静态属性并伪造其成员的包装类(适配器模式).
例如:
As a solution you can create a wrapper class (Adapter Pattern) holding the static property and fake its members.
For example:
public class HttpRuntimeWrapper
{
public virtual string AppDomainAppVirtualPath
{
get
{
return HttpRuntime.AppDomainAppVirtualPath;
}
}
}
在生产代码中,您可以访问此类而不是 HttpRuntime
并伪造此属性:
In the production code you can access this class instead of HttpRuntime
and fake this property:
[Test]
public void AppDomainAppVirtualPathTest()
{
var mock = new Moq.Mock<HttpRuntimeWrapper>();
mock.Setup(fake => fake.AppDomainAppVirtualPath).Returns("FakedPath");
Assert.AreEqual("FakedPath", mock.Object.AppDomainAppVirtualPath);
}
另一种解决方案是使用隔离框架(如Typemock Isolator),您可以在其中可以伪造静态类和成员.
例如:
Another solution is to use Isolation framework (as Typemock Isolator) in which you can fake static classes and members.
For example:
Isolate.WhenCalled(() => HttpRuntime.AppDomainAppVirtualPath)
.WillReturn("FakedPath");
免责声明 - 我在 Typemock 工作
这篇关于使用 moq 模拟静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!