0

I would like Mock user with Moq. Is it possible to mock it? Using Nunit and Moq framework. The method which I want to test is this: User 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;
        }
    }
Casper Dijkstra
  • 1,615
  • 10
  • 37
Joe People
  • 35
  • 1
  • 8
  • 1
    Kindly format your code correctly. – Ritwik Sen Aug 22 '17 at 15:00
  • Possible duplicate of [How to mock static methods in c# using MOQ framework?](https://stackoverflow.com/questions/12580015/how-to-mock-static-methods-in-c-sharp-using-moq-framework) – Owen Pauling Aug 22 '17 at 15:26
  • If you have access to MsFakes (or similar), consider shims instead of mocks. – AndrewP Aug 23 '17 at 02:20
  • 1
    There are many reasons why it may become hard to mock the above code. But you could set the `CurrentPrincipal` to some mock object for a start. `var mock = new Mock(); /* do setups */ Thread.CurrentPrincipal = mock.Object;` – Jeppe Stig Nielsen Aug 23 '17 at 07:41

0 Answers0