Mock My.User.IsInRole() error in Asp.Net MVC

Deadly 提交于 2019-12-11 12:22:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!