1

我正在对我的 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;
4

1 回答 1

2

Session 不在请求上下文中,它需要混合ICacheClientSessionFeature 和 HttpRequest cookie 来创建。

您可以查看在Service 中模拟它的方式的实现,这表明它首先尝试在 Container 中解析它:

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*/ });
于 2013-10-04T05:52:37.803 回答