在Asp.Net MVC中模拟My.User.IsInRole()错误 [英] Mock My.User.IsInRole() error in Asp.Net MVC
本文介绍了在Asp.Net MVC中模拟My.User.IsInRole()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个单元测试来模拟在以下控制器中使用的My.User.IsInRole()
,
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
尝试在此测试用例(VB代码)中设置模拟:
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
在调用GetUserRole()
时,My.User.IsInRole("Agent")
应该返回True
,但是它返回False
.我的代码有什么问题吗?
When calling GetUserRole()
, My.User.IsInRole("Agent")
should return True
, but it returns False
. Anything wrong on my code?
有关此错误的任何建议.
Any suggestion about this error.
推荐答案
您需要将模拟原理分配给当前线程原理,(下面是c#代码,希望您能解释它)
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?
这篇关于在Asp.Net MVC中模拟My.User.IsInRole()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文