unit-testing - 通过单元测试

标签 unit-testing azure servicestack

我已经为我的服务编写了单元测试。我已使用 Azure Active Directory 进行身份验证。现在,在使用 MockHttpRequest 传递 session 时,我收到异常 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),
            }
        ));

    }

最佳答案

如果您将 AppHost 设置为 TestMode,则可以使用 IOC 模拟 session :

SetConfig(new HostConfig { TestMode = true });

这将允许您注册一个 session ,该 session 在请求 session 时返回,即:

IAuthSession session = new AadAuthSession();
container.Register<IAuthSession>(c => session);

模拟 session 的另一种方法是将其注册到 IRequest.Items 中,例如:

req.Items[SessionFeature.RequestItemsSessionKey] = session;

关于unit-testing - 通过单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34064277/

相关文章:

azure - Cosmos DB 中的事件 ID 是什么?

javascript - 如何在 React 组件中 Jest 测试 lodash.get 的使用?

sql-server - 在azure sql server中隐藏特定用户的其他数据库

azure - Azure App Insights 中存在太多(已恢复)异常

ssl - Servicestack Swagger UI 端点与 UseHttpsLinks 的行为不符合预期

c# - 如何让 ServiceStack 身份验证工作? (使用 iPhone 客户端)

swift - swift中的Quick框架中的describe和context有什么区别?

java - maven测试报告格式

java - 单元测试 JAX-RS Controller 的最佳方法?

c# - 单点触控 : Using ServiceStack caused JIT error?