在单元测试中使用的HttpContext [英] Using httpcontext in unit test
问题描述
我使用C#4.0,我需要单元测试的服务。服务内的函数返回类似于我打电话预期变量的路径,这是我期待找回的路径。但是,当我运行这个测试我收到HttpContext.Current是空的错误。我能做些什么来解决这个问题,所以测试可以跑了?
[TestMethod的]
公共无效GetPathTest( )
{
VAR预期= System.IO.Path.GetFullPath(HttpContext.Current.Server.MapPath(〜/证书/));
VAR路径= _mockService.Setup(O => o.GetPath())返回(预期)。
}
目前,我可以'找不到我的HttpContext的,我前面采用全包装,但此刻,我们简单地创建一个上下文的空请求,并从那里,像这样的:
SimpleWorkerRequest的要求=新的SimpleWorkerRequest(,,,空,新的StringWriter());
HttpContext的背景下=新的HttpContext(请求);
然后在单元测试初始化或在单元测试本身(在创建之前的预期),你可以设置当前的HttpContext如下:
HttpContext.Current =背景;
然后根据要求简单地充实假的状况和可能的假的sessionState等。
(编辑:这是所有在VS2008中,框架3.5的方式)
。
I'm using C#4.0 and i need to unit test a service. The function inside the service returns a path similar to the variable i called expected, this is the path i'm expecting to get back. But when i run this test i'm getting the error that HttpContext.Current is NULL. What can i do to fix this issue so the test can be ran?
[TestMethod]
public void GetPathTest()
{
var expected = System.IO.Path.GetFullPath(HttpContext.Current.Server.MapPath("~/Certificates/"));
var path = _mockService.Setup(o => o.GetPath()).Returns(expected);
}
At the moment I can't find my full wrapper for HttpContext that I used earlier, but at the moment we simply create a context for an empty request and go from there, like this:
SimpleWorkerRequest request = new SimpleWorkerRequest("","","", null, new StringWriter());
HttpContext context = new HttpContext(request);
Then in the unit test initialize or in the unit test itself (before you create expected) you can set the current HttpContext as follows:
HttpContext.Current = context;
Then simply flesh out the fake context and possible fake sessionstate, etc as required.
(Edit: This is all in VS2008, framework 3.5 by the way).
这篇关于在单元测试中使用的HttpContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!