在单元测试中传递会话

时间:2015-12-03 11:02:43

标签: unit-testing azure servicestack

我为我的服务编写单元测试。我使用Azure Active Directory进行身份验证。现在,在使用MockHttpRequest传递会话时,我将获得异常Unable to cast object of type 'ServiceStack.AuthUserSession' to type 'AadAuthSession'.这是我在Testbase类中的代码。

  IAuthSession session = new AadAuthSession();
        session.UserName = "Author";
        appHost.Plugins.Add(new AuthFeature(() => session,
            new IAuthProvider[] {
                new AadAuthProvider(appHost.AppSettings),
            }
   ));

我错过了什么..如何正确投射?

public TestBase()
    {
        appHost = new TestAppHost().Init();
        appHost.TestMode = true;
        appHost.AppSettings = new AppSettings();
        appHost.Container.Register<IDbConnectionFactory>(
            new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
        appHost.Container.Register<ICacheClient>(new MemoryCacheClient());

        IAuthSession session = new AadAuthSession();
        appHost.Container.Register<IAuthSession>(c => session);
        session.UserName = "Author";
        appHost.Plugins.Add(new AuthFeature(() => session,
            new IAuthProvider[] {
                new AadAuthProvider(appHost.AppSettings),
            }
        ));

    }

1 个答案:

答案 0 :(得分:2)

如果您将AppHost设置为$.get('http://localhost:3000/api/data', function(data){ // handle that 'data' on the client side here // ... // ... }); ,则可以使用IOC模拟会话:

TestMode

这将允许您注册在请求会话时返回的会话,即:

SetConfig(new HostConfig { TestMode = true });

模拟会话的另一种方法是在IAuthSession session = new AadAuthSession(); container.Register<IAuthSession>(c => session); 中注册它,例如:

IRequest.Items