模拟静态属性MOQ [英] Mock static property with moq
问题描述
我是pretty新使用起订量。我到创造一些单元测试用例的HttpModule
,一切工作正常,直到我打了一个静态
属性如下:
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;
我不知道如何创建静态
类和属性如 HttpRuntime.AppDomainAppVirtualPath
嘲弄。在背景
,要求
和响应
与已嘲笑很好样品code,我从起订量得到。我将AP preciate如果有人能帮助我在此。
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 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;
}
}
}
在生产code,你可以访问这个类,而不是的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隔离),其中可以伪造静态类和成员。结果
例如:
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屋!