Unit Test ServiceClass1 has challenge in Mocking Session, SessionBag in .Net 8.0 class Library Project Target 4.7.1 and .Net 8.0

Unit Test ServiceClass1 that calls “GetCurrentUserIsImpersonating” method of the “HttpContextWrapper” class which calls the “IsImpersonating” extension method in the “UserIdentityExtensions” static class, which relies on the SessionBag.Current.Impersonator value. it call TrGetMember in SessionBag and exit when execute Current.Session != null. Added set here private static ISession Session
Removed interval in set if Public static dynamic Current.

The .Net Framework 4.7.1 Unit test pass but the .Net core 8.0 unit test fails becuase challenge to mock the SessionBag.Current.

The followig code is the unit test mocking part
but it exit from unit test when execute SessionBag.Current.Session = mockSession.Object; give this in output.

The program ‘[26852] testhost.exe’ has exited with code 3221225477 (0xc0000005) ‘Access violation’.

Please advise.

**Unit Test Mocking Part**
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();

// Create a DefaultHttpContext (this will automatically have Request, Response, etc.)
var httpContext = new DefaultHttpContext();

// Create HttpRequest and configure its properties
var request = httpContext.Request;
request.Scheme = "https";
request.Host = new HostString("www.test.com");
request.Path = "/somepath";
request.QueryString = QueryString.Empty;
request.Method = "GET"; // Set the HTTP method


// Create a ClaimsIdentity and add claims (including the ones IsImpersonating may check)
var claimsIdentity = new ClaimsIdentity();
claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, "TestUser"));
claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
claimsIdentity.AddClaim(new Claim("ImpersonatorClaim", "SomeValue"));

// Create a ClaimsPrincipal with the mocked ClaimsIdentity
var claimsPrincipal = new Mock<ClaimsPrincipal>();
claimsPrincipal.Setup(p => p.HasClaim(It.Is<Predicate<Claim>>(pred =>
    pred(new Claim("ImpersonatorClaim", "SomeValue"))))).Returns(true);

// Assign the mocked ClaimsPrincipal to HttpContext.User
httpContext.User = claimsPrincipal.Object;

// Set up the HttpContextAccessor mock to return the httpContext
mockHttpContextAccessor.Setup(a => a.HttpContext).Returns(httpContext);

var mockSession = new Mock<ISession>();
var mockPrincipal = new Mock<IPrincipal>();

// Setup mock session behavior
mockSession.Setup(s => s.TryGetValue(It.IsAny<string>(), out It.Ref<byte[]>.IsAny))
    .Returns(true)
    .Callback((string key, out byte[] value) =>
    {
        if (key == "Impersonator")
        {
            value = new byte[] { 1, 2, 3 }; // Example byte array
        }
        else
        {
            value = null;
        }
    });

// Initialize SessionBag with the mock session
SessionBag.Current = new SessionBag();
var sessionProperty = typeof(SessionBag).GetProperty("Session", BindingFlags.Static | BindingFlags.NonPublic);
if (sessionProperty != null && sessionProperty.CanWrite)
{
    sessionProperty.SetValue(null, mockSession.Object);
}

if (SessionBag.Current == null)
{
    SessionBag.Current = new SessionBag();  // Initialize it properly
}

// Mock the session object
var mockSession = new Mock<ISession>();
mockSession.Setup(s => s.TryGetValue(It.IsAny<string>(), out It.Ref<byte[]>.IsAny)).Returns(true);

// Set the mock session to the SessionBag
SessionBag.Current.Session = mockSession.Object;

// Act
var result = mockPrincipal.Object.IsImpersonating();

HttpContextWrapper.Configure(mockHttpContextAccessor.Object, "");



**HttpContextWrapper class**

#if NET8_0_OR_GREATER
using System;
using System.Web.Mvc;
using Microsoft.AspNetCore.Http;
#else
using System;
using System.Web;
#endif

namespace Tools
{
    public static class HttpContextWrapper
    {
#if NET8_0_OR_GREATER
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
        private static string WebRootPath { get; }

        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor, string webRootPath)
        {
            m_httpContextAccessor = httpContextAccessor;
        }
        public static bool CheckAccessorIsNull()
        {
            return m_httpContextAccessor == null;
        }
        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                if (m_httpContextAccessor != null)
                {
                    return m_httpContextAccessor.HttpContext;
                }
                else
                {
                    return null;
                }
            }
        }
        public static bool CurrentUserIsLoggedIn()
        {
            return Current != null;
        }
        public static string GetImpersonatorName()
        {
            return Current.User.Identity.ImpersonatorName().ToUpper();
        }
        public static bool CurrentUserIsAuthenticated()
        {
            if (Current != null)
            {
                return Current.User.Identity.IsAuthenticated;
            }
            else
            {
                return false;
            }
        }

        public static bool GetCurrentUserIsImpersonating()
        {
            if (Current != null)
            {
                return Current.User.IsImpersonating();
            }
            else
            {
                return false;
            }
        }

        public static string GetCurrentUser()
        {
            return Current.User.Identity.Name.ToUpper();
        }

        public static bool IsInRole(string role)
        {
            return Current.User.IsInRole(role);
        }

        public static string GetFile(string filePath)
        {
            return string.Concat(WebRootPath, filePath);
        }

        public static string GetBaseUrl()
        {
            var uri = string.Empty;
            var port = Current.Request.Host.Port;

            if (port != null)
            {
                uri = Current.Request.Host.ToString().Replace(port.ToString(), string.Empty);
            }
            else
            {
                uri = Current.Request.Host.ToString();
            }

            return uri;
        }
#else
        public static bool CurrentUserIsLoggedIn()
        {
            return HttpContext.Current != null;
        }

        public static string GetImpersonatorName()
        {
            return HttpContext.Current.User.Identity.ImpersonatorName().ToUpper();
        }

        public static bool CurrentUserIsAuthenticated()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        public static bool GetCurrentUserIsImpersonating()
        {
            return HttpContext.Current.User.IsImpersonating();
        }

        public static string GetCurrentUser()
        {
            return HttpContext.Current.User.Identity.Name.ToUpper();
        }

        public static bool IsInRole(string role)
        {
            return HttpContext.Current.User.IsInRole(role);
        }

        public static string GetFile(string filePath)
        {
            return HttpContext.Current.Server.MapPath(filePath);
        }
#endif
    }
}

**UserIdentityExtensions**


  public static class UserIdentityExtensions
   {
       public static bool IsImpersonating(this IPrincipal principal)
       {
           if (SessionBag.Current.Impersonator == null)
           {
               return false;
           }

           var impersonator = SessionBag.Current.Impersonator as string;
           if (string.IsNullOrWhiteSpace(impersonator))
           {
               return false;
           }

           return true;
       }
       public static string ImpersonatorName(this IIdentity identity)
       {
           if (SessionBag.Current.Impersonator == null)
           {
               return string.Empty;
           }

           var impersonator = SessionBag.Current.Impersonator as string;
           if (string.IsNullOrWhiteSpace(impersonator))
           {
               return string.Empty;
           }

           return impersonator.ToUpper();
       }
   }

**SessionBag class**

namespace Helper
{
    using System;
    using System.Collections.Generic;
    using System.Dynamic;
    using System.Web;
    using Microsoft.AspNetCore.Http;
    [Serializable]
    public class SessionBag : DynamicObject
    {
        private static SessionBag current;
        static SessionBag()
        {
            current = new SessionBag();
        }
        public static dynamic Current
        {
            get
            {
                return current;
            }

            internal set
            {
                current = value;
            }
        }
#if NET8_0_OR_GREATER
        private static ISession Session
        {
            get
            {
                var session = Current.Session;
                return session;
            }
        }

#else
        private static HttpSessionStateBase Session
        {
            get
            {
                var session = System.Web.HttpContext.Current.Session;
                return new HttpSessionStateWrapper(session);
            }
        }
#endif
#if NET8_0_OR_GREATER
        public object this[string name]
        {
            get
            {
                Session.TryGetValue(name,out byte[] val);
                return val;
            }

            set
            {
                Session.Set(name, (byte[])value);
            }
        }
#else
        public object this[string name]
        {
            get
            {
                return Session[name];
            }

            set
            {
                Session[name] = value;
            }
        }
#endif
        public static void Remove(string key)
        {
            Session.Remove(key);
        }
        public static void Add(string key, object value)
        {
#if NET8_0_OR_GREATER
            Session.Set(key, (byte[])value);
#else
            Session.Add(key, value);
#endif
        }
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
#if NET8_0_OR_GREATER
            if (Current.Session != null)
            {
                Session.TryGetValue(binder.Name,out byte[] val);
                result = val;
#else
            if (System.Web.HttpContext.Current.Session != null)
              {
                result = Session[binder.Name];
#endif
            }
            else
            {
                result = null;
            }

            return true;
        }
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            this[binder.Name] = value;
            return true;
        }
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
#if NET8_0_OR_GREATER
                Session.TryGetValue(binder.Name,out byte[] val);
                result=val; 
#else
                result = Session[binder.Name];

#endif
                if (result == null)
                {
                    result = args[0];
                }

                return true;
            }
            catch
            {
                return base.TryInvokeMember(binder, args, out result);
            }
        }
        public override IEnumerable<string> GetDynamicMemberNames()
        {
            var keys = new List<string>();
            foreach (var key in Session.Keys)
            {
                keys.Add(key.ToString());
            }

            return keys;
        }
        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            return base.TryConvert(binder, out result);
        }
    }
}



2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật