如何在没有ControllerContext的情况下模拟来自IIdentity的GetUserId和IsAuthenticated

时间:2016-05-16 23:54:14

标签: c# unit-testing mocking ninject

Mock IIdentity.GetUserId和IIdentity.IsAuthenticated有一个简单的方法吗?

我已经通过这种方式测试并获得了 NotSupportedException

[Test]
public void CanGetUserIdFromIdentityTest()
{
    //Enviroment
    var mockIdentity = new Mock<IIdentity>();
    mockIdentity.Setup(x => x.Name).Returns("test@test.com");
    mockIdentity.Setup(x => x.IsAuthenticated).Returns(true);
    mockIdentity.Setup(x => x.GetUserId()).Returns("12345");

    var mockPrincipal = new Mock<IPrincipal>();
    mockPrincipal.Setup(x => x.Identity).Returns(mockIdentity.Object);
    mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);

    //Action
    Kernel.Rebind<IPrincipal>().ToConstant(mockPrincipal.Object);

    //Asserts
    var principal = Kernel.Get<IPrincipal>();
    Assert.IsNotNull(principal.Identity.GetUserId());
    Assert.IsTrue(principal.Identity.IsAuthenticated);
}

我也使用 GenericIdentity 进行了测试。使用它我可以模拟 GetUserId(),但我无法模拟 IsAuthenticated 属性。

任何人都可以帮助我?

1 个答案:

答案 0 :(得分:2)

您获得了barrier,因为mem_fence是来自 IdentityExtensions.GetUserId Method 的扩展方法,并且不属于模拟对象。无需模拟NotSupportedException

如果您查看GetUserId的源代码,您会看到它对您不起作用。

GetUserId

它正在寻找GetUserId /// <summary> /// Extensions making it easier to get the user name/user id claims off of an identity /// </summary> public static class IdentityExtensions { /// <summary> /// Return the user name using the UserNameClaimType /// </summary> /// <param name="identity"></param> /// <returns></returns> public static string GetUserName(this IIdentity identity) { if (identity == null) { throw new ArgumentNullException("identity"); } var ci = identity as ClaimsIdentity; if (ci != null) { return ci.FindFirstValue(ClaimsIdentity.DefaultNameClaimType); } return null; } /// <summary> /// Return the user id using the UserIdClaimType /// </summary> /// <param name="identity"></param> /// <returns></returns> public static string GetUserId(this IIdentity identity) { if (identity == null) { throw new ArgumentNullException("identity"); } var ci = identity as ClaimsIdentity; if (ci != null) { return ci.FindFirstValue(ClaimTypes.NameIdentifier); } return null; } /// <summary> /// Return the claim value for the first claim with the specified type if it exists, null otherwise /// </summary> /// <param name="identity"></param> /// <param name="claimType"></param> /// <returns></returns> public static string FindFirstValue(this ClaimsIdentity identity, string claimType) { if (identity == null) { throw new ArgumentNullException("identity"); } var claim = identity.FindFirst(claimType); return claim != null ? claim.Value : null; } } ,这就是ClaimsIdentity的原因。这意味着您需要创建Identity的存根。为了使ClaimTypes.NameIdentifier起作用,您只需在构造函数中提供身份验证类型。空字符串可以工作。

以下是您带有更改的测试方法

GenericIdentity