代码之家  ›  专栏  ›  技术社区  ›  Don Fitz

ServiceStack MockRequestContext自定义身份验证用户会话

  •  1
  • Don Fitz  · 技术社区  · 11 年前

    我正在单元测试我的API服务,使用MockRquestContext一切都很好。对this.GetSession()的调用总是返回一个IAuthSession,但我有一个自定义的AuthUserSession,据我所知,没有办法创建我的自定义AuthUserSession的实例并将其添加到模拟上下文中。这可能吗?

    var service = container.Resolve<AgencyCaseService>();
            service.SetResolver(new BasicResolver(container));
    
            var context = new MockRequestContext() { ResponseContentType = ContentType.Json };
            //Something like this
            MyCustomAuthSession session = new MyCustomAuthSession() { set some values}
    
            context.AuthSession = session//this doesn't exist but it's the type of thing i need to do
    
            service.RequestContext = context;
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   mythz    11 年前

    会话不在请求上下文中,它需要 ICacheClient ,要创建的SessionFeature和HttpRequest cookie。

    您可以查看实现的方法 mock it inside a Service ,显示它首先尝试在容器中解析它:

    private object userSession;
    protected virtual TUserSession SessionAs<TUserSession>()
    {
        if (userSession == null)
        {
            userSession = TryResolve<TUserSession>(); //Easier to mock
            if (userSession == null)
                userSession = Cache.SessionAs<TUserSession>(Request, Response);
        }
        return (TUserSession)userSession;
    }
    

    所以要嘲笑它,你可以这样做:

    container.Register(new MyCustomAuthSession() { /* set some values*/ });