Reputation: 83
I have a unit test to mock both My.User.IsInRole() and ClaimsPrincipal in the following controller.
The current thread principle has been assigned twice, therefore only the second ClaimPrincipal is working, how can I do to make both mock principle working?
Public Class TestController
Public Function GetUserDetail() As String
If My.User.IsInRole("Agent") Then
result = "Login as Agent"
End If
If ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value = "[email protected]" Then
result = result & " and Claim name is correct"
End If
Return result
End Function
End Class
trying to set up the mock in this test case (VB code, C# is ok too):
<TestMethod()>
Public Sub Test()
//Arrange
//Mock User.IsInRole():
Dim fakePrincipal = New Moq.Mock(Of IPrincipal)()
fakePrincipal.Setup(Function(p) p.IsInRole("Agent")).Returns(True)
Thread.CurrentPrincipal = fakePrincipal.[Object]
'Dim fakeClaimPrincipal = New Mock(Of ClaimsPrincipal)()
'Dim claims As IEnumerable(Of Claim) = New List(Of Claim) ().AsEnumerable()
'fakeClaimPrincipal.Setup(Sub(e) e.Claims).Returns(claims)
'Thread.CurrentPrincipal = fakeClaimPrincipal.[Object]
//Mocking is not working on ClaimsPrincipal.FindFirst(), so it's fixed
by using claim based function:
Thread.CurrentPrincipal = New TestPrincipal(New Claim(ClaimTypes.Name, "[email protected]"))
Public Class TestPrincipal
Inherits ClaimsPrincipal
Public Sub New(ParamArray claims As Claim())
MyBase.New(New TestIdentity(claims))
End Sub
End Class
Public Class TestIdentity
Inherits ClaimsIdentity
Public Sub New(ParamArray claims As Claim())
MyBase.New(claims)
End Sub
End Class
// Act
Dim result = TestController.GetUserDetail()
End Sub
So one is mock principal, the other one is not mock principal, how do I assign the current thread?
Upvotes: 0
Views: 657
Reputation: 247471
The second mock is overriding the first one that was set on the thread.
Use the mocked ClaimsPrincipal
and setup necessary members
<TestMethod()>
Public Sub Test()
//Arrange
Dim fackClaimPrinciple = New Mock(Of ClaimsPrincipal)()
Dim claims As IEnumerable(Of Claim) = New List(Of Claim) ().AsEnumerable()
fackClaimPrinciple.Setup(Sub(e) e.Claims).Returns(claims)
fackClaimPrinciple.Setup(Function(p) p.IsInRole("Agent")).Returns(True)
Thread.CurrentPrincipal = fackClaimPrinciple.[Object]
// Act
Dim result = TestController.GetUserDetail()
End Sub
Upvotes: 1