Unit Test ServiceClass1 hat eine Herausforderung in Mocking Session, SessionBag in .Net 8.0 Class Library Project TargetC#

Ein Treffpunkt für C#-Programmierer
Guest
 Unit Test ServiceClass1 hat eine Herausforderung in Mocking Session, SessionBag in .Net 8.0 Class Library Project Target

Post by Guest »

Unit Test ServiceClass1, der die Methode „GetCurrentUserIsImpersonating“ der Klasse „HttpContextWrapper“ aufruft, die die Erweiterungsmethode „IsImpersonating“ in der statischen Klasse „UserIdentityExtensions“ aufruft, die auf dem Wert SessionBag.Current.Impersonator basiert. Es ruft TrGetMember in SessionBag auf und wird beendet, wenn Current.Session != null ausgeführt wird. Satz hier hinzugefügt: private statische ISession-Sitzung
Intervall im Satz entfernt, wenn öffentlicher statischer dynamischer Strom.
Der .Net Framework 4.7.1-Einheitentest besteht, aber der .Net Der Unit-Test von Core 8.0 schlägt fehl, weil die Herausforderung besteht, SessionBag.Current zu verspotten.
Der folgende Code ist der Teil zum Verspotten des Unit-Tests,
aber er verlässt den Unit-Test, wenn er ausgeführt wird SessionBag.Current.Session = mockSession.Object; geben Sie dies in der Ausgabe aus.
Das Programm „[26852] testhost.exe“ wurde mit dem Code 3221225477 (0xc0000005) „Access Verstoß‘.
Bitte informieren Sie uns.
**Unit Test Mocking Part**
var mockHttpContextAccessor = new Mock();

// 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.Setup(p => p.HasClaim(It.Is(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();
var mockPrincipal = new Mock();

// Setup mock session behavior
mockSession.Setup(s => s.TryGetValue(It.IsAny(), out It.Ref.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();
mockSession.Setup(s => s.TryGetValue(It.IsAny(), out It.Ref.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 GetDynamicMemberNames()
{
var keys = new List();
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);
}
}
}

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post