问题
I have a unit test to mock My.User.IsInRole()
used in the following controller,
Public Class BookingController
Public Function GetUserRole() As String
If My.User.IsInRole("Agent") Then
result = "Login as Agent"
End If
```
End Function
End Class
trying to set up the mock in this test case (VB code):
<TestMethod()>
Public Sub Test()
//Arrange
'Dim httpContext = New Mock(Of System.Web.HttpContextBase)()
Dim principal = New Moq.Mock(Of IPrincipal)()
'httpContext.Setup(Function(x) x.User).Returns(principal.[Object])
principal.Setup(Function(p) p.IsInRole("Agent")).Returns(True)
Thread.CurrentPrincipal = principal.[Object]
// Act
Dim result = controller.GetUserRole()
End Sub
When calling GetUserRole()
, My.User.IsInRole("Agent")
should return True
, but it returns False
. Anything wrong on my code?
Any suggestion about this error.
回答1:
You need to assign principle mock to current thread principle, (Below is c# code I hope you can interpret it)
// Make fack principle instance
var fackPrinciple = new Mock<IPrinciple>();
// Setup fack data
fackPrinciple.Setup(e => e.IsInRole(It.IsAny<String>)).Returns(true);
// Assign to current thread principle
Thread.CurrentPrincipal = fackPrinciple.Object;
Please let me know if have any issue?
来源:https://stackoverflow.com/questions/50117783/mock-my-user-isinrole-error-in-asp-net-mvc