Unit Testing GetSession

Per the documentation, I have written unit tests for my services as:

_appHost = new BasicAppHost().Init();
var container = _appHost.Container;
container.RegisterAutoWired<MyService>();
MyService service = _appHost.Container.Resolve<MyService>();

this works fine generally, however, one of my APIs calls GetSession().UserName to get the username of the current authenticated user so that I know who is using the API and can return him appropriate data. When I execute this line of code in my unit test, I get an exception:

‘GetSession()’ threw an exception of type ‘System.NotImplementedException’
“This AppHost does not support accessing the current Request via a Singleton”

How can I unit test this service?

1 Like

You need to inject or mock a IRequest context for Services that depends on the request context like Sessions.

You should be able to mock a Session with something like:

service.Request = new BasicRequest { 
    Verb = HttpMethods.Post, 
    Items = {
        [Keywords.Session] = new AuthUserSession { ... }
    }
};

Note: the recommended API to resolve a Service is:

var req = new BasicRequest { 
    Verb = HttpMethods.Post, 
    Items = {
        [Keywords.Session] = new AuthUserSession { ... }
    }
};

using (var service = HostContext.ResolveService<MyService>(req))
{
    //..
}
1 Like

thanks as always for the quick response!