在HttpSessionStateBase c#unit test中获取null

时间:2017-01-16 10:44:21

标签: c# unit-testing mocking httprequest httpsession

在运行我的单元测试方法时,我在HttpSessionStateBase的实例中获取空值。我像这样嘲笑httpcontext

var httpRequest = new HttpRequest("", "http://localhost/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer("id", 
                                                     new SessionStateItemCollection(),
                                                     new HttpStaticObjectsCollection(), 
                                                     10, 
                                                     true,
                                                     HttpCookieMode.AutoDetect,
                                                     SessionStateMode.InProc, 
                                                     false);

SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);

请提出一些建议,以便在HttpSessionStateBase中获取一些虚拟值

1 个答案:

答案 0 :(得分:3)

假设您有以下控制器操作,您需要进行单元测试:

public class AccountController: Controller
{
    public ActionResult Login(Customer obj)
    {
        Session.Clear();
        return View();
    }
}

这是一个示例连线:

// arrange
var httpRequest = new HttpRequest("", "http://localhost/", "");
var stringWriter = new StringWriter();
var httpResponse = new HttpResponse(stringWriter);
var httpContext = new HttpContext(httpRequest, httpResponse);
var sessionContainer = new HttpSessionStateContainer(
    "id",
    new SessionStateItemCollection(),
    new HttpStaticObjectsCollection(),
    10,
    true,
    HttpCookieMode.AutoDetect,
    SessionStateMode.InProc,
    false);
SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);

var controller = new AccountController();
var requestContext = new RequestContext(new HttpContextWrapper(httpContext), new RouteData());
controller.ControllerContext = new ControllerContext(requestContext, controller);

// act
var actual = controller.Login(new Customer());

// assert
...

请注意,您需要在调用操作之前填充controller.ControllerContext属性。