我有一个单元测试来模拟以下控制器中使用的My.User.IsInRole()
,
Public Class BookingController
Public Function GetUserRole() As String
If My.User.IsInRole("Agent") Then
result = "Login as Agent"
End If
```
End Function
End Class
尝试在此测试用例中设置模拟(VB代码):
<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
致电GetUserRole()
时,My.User.IsInRole("Agent")
应返回True
,但会返回False
。我的代码有什么问题吗?
有关此错误的任何建议。
答案 0 :(得分:2)
你需要将原理模拟分配给当前的线程原理,(下面是c#代码我希望你能解释它)
// 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;
如果有任何问题,请告诉我?