我正在为 ASP.NET 5.x 的项目使用 asp.net 样板。我正在尝试为这个项目创建测试用例,它将调用现有的测试数据库(一个用于主机的数据库,另一个用于租户的数据库)。到目前为止,我的步骤是:
- 在
TestBase
类构造函数中,我调用的方法与为MultiTenantMigrateExecuter.Run()
测试主机数据库和测试租户数据库播种数据的方法相同(我将使用主机数据库和单个租户数据库进行测试)。播种将与真实数据库相同,只是测试数据库的名称不同。 - 同样从
TestBase
类构造函数中,我从主机数据库中获取 TenantId。 - 接下来,我试图从租户数据库中获取任何种子用户,如下所示:
var user= UsingDbContext(context => context.Users.FirstOrDefault(t => t.UserName== "johndoe"));
但当然这将调用 HostDb 而不是 TenantDb。
我找到了一种调用 TenantDb 的方法,方法是将代码包装在这样的 using 语句中,避免使用context
和使用存储库,以便能够从 TenantDb 获取我需要的用户:
using (this.AbpSession.Use(tenant.Id, null))
{
// get the TenantDb.User here by using the User repository
}
...然后在我编写的每个测试用例中都这样:
using (this.AbpSession.Use(AbpSession.TenantId, AbpSession.UserId))
{
// make calls to the Tenant database here by using Tenant repository
}
但这不是最干净的解决方案,它有其局限性。
问题是:在我的情况下是否有更好的方法,在TestBase
类中设置上下文以默认调用租户数据库而不是主机数据库?
我也试过这个,但它不起作用......
protected T UsingTenantDbContext<T>(Func<TestAppDbContext, T> func)
{
T result;
using (this.AbpSession.Use(AbpSession.TenantId, AbpSession.UserId))
{
using (var context = LocalIocManager.Resolve<TestAppDbContext>())
{
context.DisableAllFilters();
result = func(context);
context.SaveChanges();
}
}
return result;
}