与Moq模拟身份

时间:2017-08-22 14:58:35

标签: mocking moq claims-based-identity asp.net-identity-2

我希望Mock用户使用Moq。有可能嘲笑吗?使用Nunit和Moq框架。 想要测试的方法是:用户user = MyProjectIdentity.Current;

public static class MyProjectIdentity
    {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();

        public static User Current => Resolve((ClaimsPrincipal)Thread.CurrentPrincipal);

        public static User Resolve(IPrincipal principal)
        {
            User result = null;
            try
            {
                var claimsPrincipal = (ClaimsPrincipal)principal;
                var userManager = UnityConfig.GetConfiguredUnityContainer().Resolve<IUsersManager>();
                FetchStrategy<User> fetchStrategy = new FetchStrategy<User>().Include(u => u.MyRoles.Select(r => r.Role))
                                                                             .Include(u => u.MyMarkets.Select(m => m.Market));
                string cdsId = ExtractCdsId(claimsPrincipal);
                result = Task.Run(() => userManager.FindUser(cdsId, fetchStrategy)).Result;
            }
            catch (Exception exception)
            {
                Log.Warn(exception, "Resolving Pricing Identity failed.");
            }

            return result;
        }

private static string ExtractCdsId(IPrincipal principal)
        {
            var claimsPrincipal = (ClaimsPrincipal)principal;

            return claimsPrincipal.Claims?.SingleOrDefault(claim => claim.Type == "CDSID")?.Value ?? string.Empty;
        }
    }

0 个答案:

没有答案