gpt4 book ai didi

.net - 如何在单元测试 .net 中模拟 ClaimsPrincipal

转载 作者:行者123 更新时间:2023-12-05 02:16:22 25 4
gpt4 key购买 nike

我正在对我的 Controller 方法对来自 ClaimsPrincipal 对象的信息进行单元测试,但是 Current.FindFirst() 没有返回任何内容,有人可以帮忙吗?谢谢。 (也可以用 VB 和 C# 编写):

  Public Class TestController
Public Function GetEmail() As String
Return ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value
End Function
End Class

<TestMethod()>
Public Sub Test()
//Arrange
Dim fackClaimPrinciple = New Mock(Of ClaimsPrincipal)()
Dim claims = New List(Of Claim)() From {New Claim(ClaimTypes.Name, "user@hotmail.com")}
fackClaimPrinciple.Setup(Function(e) e.Claims).Returns(claims)
Thread.CurrentPrincipal = fackClaimPrinciple.[Object]

// Act
Dim result = TestController.GetEmail()

'... ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value Returns nothing??

End Sub

最佳答案

您可以将声明原则分配给当前线程原则,

        // Make fack claims principle instance
var fackClaimPrinciple = new Mock<ClaimsPrincipal>();

// Setup fack data
IEnumerable<Claim> claims = new List<Claim>() {
new Claim(ClaimTypes.Name, "user@hotmail.com")
}.AsEnumerable();
fackClaimPrinciple.Setup(e => e.Claims).Returns(claims);

// Assign to current thread principle
Thread.CurrentPrincipal = fackClaimPrinciple.Object;

// Act
ViewResult result = homeController.Index() as ViewResult;

// Assert
Assert.IsNotNull(result);

关于.net - 如何在单元测试 .net 中模拟 ClaimsPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50034918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com