【发布时间】:2014-05-28 03:34:17
【问题描述】:
给定以下函数:
public static void Write(HttpContextBase contextBase, IUnitOfWork unitOfWork, LogLevel level, string title, string message, params AdditionalProperty[] properties)
{
// Some variables that are set for writing the logs.
// - client: When the HttpContext is null, 'N.A.' is used, otherwise the I.P. address of the requesting computer.
// - userIdentifier: When the HttpContext exists and a value is stored in the cookie, the value of the cookie, otherwise an empty guid.
// - requestIdentifier: When the context is existing and a request have been made on a controller, a unique value identifying this request, otherwise an empty guid.
string client = (contextBase.ApplicationInstance == null || contextBase.ApplicationInstance.Context.CurrentHandler == null) ? "N.A." : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
string userIdentifier = (contextBase.ApplicationInstance != null && contextBase.ApplicationInstance.Context != null && contextBase.ApplicationInstance.Context.CurrentHandler != null && CookieManager.Exists("UserIdentifier")) ? CookieManager.Read("UserIdentifier", Guid.NewGuid().ToString().ToUpper()) : Guid.Empty.ToString();
string requestIdentifier = (contextBase.ApplicationInstance != null && contextBase.ApplicationInstance.Context != null && contextBase.ApplicationInstance.Context.Cache != null && HttpContext.Current.Cache["RequestIdentifier"] != null) ? HttpContext.Current.Cache["RequestIdentifier"].ToString() : Guid.Empty.ToString();
// Additional code for processing is done here.
}
我正在为工作单元使用 HttpContextBase 和接口,因为我知道它比单元测试更容易。
现在我正在使用 Moq 在我的单元测试中使用 Mocking 功能,我正在努力解决它。
让我们看看变量client:
string client = (contextBase.ApplicationInstance == null || contextBase.ApplicationInstance.Context.CurrentHandler == null) ? "N.A." : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
我想知道如何通过模拟必要的对象来设置我的单元测试。
这是我当前的单元测试:
var context = new Mock<HttpContextBase>();
var httpApplicationMock = new Mock<HttpApplication>();
httpApplicationMock.SetupGet(x => x.Context).Returns(context.Object); --> FAILS
context.SetupGet(c => c.ApplicationInstance).Returns(httpApplicationMock.Object);
httpApplicationMock 设置失败,因为 context.Object 不是有效参数,但我需要传入 HttpContext。
有人可以向我轻轻推动一下正确的方向吗?
【问题讨论】:
标签: c# unit-testing mocking moq