Unit Test SessionAs

I’m trying to mock a custom user session but getting a Unable to cast object of type ‘ServiceStack.AuthUserSession’ to type CustomUserSession when Im call SessionAs

Here is my test setup

 public class UnitTest
    private readonly ServiceStackHost appHost;
    private readonly BasicRequest authenticatedRequest;
    private readonly MyServices myService;
    public UnitTest()
        appHost = new BasicAppHost().Init();

        authenticatedRequest  = new BasicRequest
            Items = {
                [Keywords.Session] = new CustomUserSession { FirstName = "user", IsAuthenticated = true}

    public void OneTimeTearDown() => appHost.Dispose();

    public void Can_call_MyServices()
        using (var service = HostContext.ResolveService<MyServices>(authenticatedRequest))
            var response = (HelloResponse)service.Any(new Hello { Name = "World" });

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));


Are there steps I have missed?


Does your CustomAuthUserSession inherit from AuthUserSession?

And have you registered it with your Auth Features?

Plugins.AddRange(new IPlugin[] {
new AuthFeature(() => new CustomAuthUserSession(), new IAuthProvider[]
                    new CustomAuthProvider()
                        PersistSession = true
1 Like

Yes my CustomUserSession inherits AuthUserSession.

Do I have to register a CustomAuthProvider? I tried it with BasicAuthProvider and it still fails the test when calling SessionAs

I figured it out I was missing the line

        appHost.Container.Register<IAuthSession>(c => new CustomUserSession { FirstName = "user", IsAuthenticated = true});