我已经为我的服务编写了单元测试。我已使用 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/