如何在单元测试.net

时间:2018-04-26 04:38:33

标签: .net asp.net-mvc vb.net unit-testing

我在我的控制器方法上对来自ClaimsPrincipal对象的信息进行单元测试,但是Current.FindFirst()没有返回任何内容,任何人都可以帮忙吗?谢谢。 (用VB和C#编写也是可以接受的):

  Public Class TestController
    Public Function GetEmail() As String
         Return ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value
    End Function
  End Class

<TestMethod()>
Public Sub Test()
  //Arrange
    Dim fackClaimPrinciple = New Mock(Of ClaimsPrincipal)()
    Dim claims = New List(Of Claim)() From {New Claim(ClaimTypes.Name, "user@hotmail.com")}
    fackClaimPrinciple.Setup(Function(e) e.Claims).Returns(claims)
    Thread.CurrentPrincipal = fackClaimPrinciple.[Object]

  // Act
  Dim result = TestController.GetEmail()

  '... ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value Returns nothing??

End Sub

2 个答案:

答案 0 :(得分:2)

您可以将声明原则分配给当前线程原则,

        // Make fack claims principle instance
        var fackClaimPrinciple = new Mock<ClaimsPrincipal>();

        // Setup fack data
        IEnumerable<Claim> claims = new List<Claim>() {
            new Claim(ClaimTypes.Name, "user@hotmail.com")
        }.AsEnumerable();
        fackClaimPrinciple.Setup(e => e.Claims).Returns(claims);

        // Assign to current thread principle
        Thread.CurrentPrincipal = fackClaimPrinciple.Object;            

        // Act
        ViewResult result = homeController.Index() as ViewResult;

        // Assert
        Assert.IsNotNull(result);

答案 1 :(得分:0)

Mocking无法处理ClaimsPrincipal.FindFirst(),因此使用基于声明的函数进行修复:

Public Class TestIdentity
    Inherits ClaimsIdentity
    Public Sub New(ParamArray claims As Claim())
        MyBase.New(claims)
    End Sub
End Class

Public Class TestPrincipal
    Inherits ClaimsPrincipal
    Public Sub New(ParamArray claims As Claim())
        MyBase.New(New TestIdentity(claims))
    End Sub
End Class

Thread.CurrentPrincipal = New TestPrincipal(New Claim(ClaimTypes.Name, "user@hotmail.com"))