-->

模拟的IIdentity和IPrincipal的(Mock IIdentity and IPrinc

2019-09-01 06:48发布

我只想问什么是更好的办法在我的单元测试来提供这些对象。

在我的单元测试我测试CSLA对象。 CSLA对象在内部使用一个属性和ApplicationUser对象的一种方法。 ApplicationUser从IPrincipal的继承。 的属性是:1)ApplicationContext.User.IsInRole(...) - 该方法是的IPrincipal 2的一部分)ApplicationContext.User.Identity.Name - 名称是作为ApplicationUser的一部分又名IPricipal的IIdentity的属性

我测试(使用RhinoMock)的实施例:

public void BeforeTest()
{
   mocks = new MockRepository();
   IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>();
   ApplicationContext.User = mockPrincipal;
   using (mocks.Record()) {
      Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true);
      Expect.Call(mockPrincipal.Identity.Name).Return("ju"); //doesn't work!!!! return null ref exc
   }
}

我有第二个值,标识名称轻微的问题。 我试着模拟它,但有问题嘲笑的IIdentity分配给ApplicationUser,因为它是internaly完成。 有人告诉我,只是我自己创造一些IIPrincipal(包括IIdentity的),而不是嘲笑它。 这可以肯定地完成。 不知道这是否可以使用被称为存根?

所以,你能指点我如何处理的IPrincipal和IIdentity的? 任何建议深受欢迎。

Answer 1:

你得到一个空引用错误的原因是因为IPrincipal.Identity为null; 它不是在你的嘲笑中设置IPrincipal呢。 调用.NameIdentity在你的异常结果。

答案,如卡尔顿指出,是嘲笑IIdentity ,并进行设置,返回“菊”为它的Name属性。 那么你可以告诉IPrincipal.Identity返回模拟IIdentity

这里是你的代码来做到这一点(使用犀牛制品,而非存根)的扩展:

public void BeforeTest()
{
   mocks = new MockRepository();
   IPrincipal mockPrincipal = mocks.CreateMock<IPrincipal>();
   IIdentity mockIdentity = mocks.CreateMock<IIdentity>();
   ApplicationContext.User = mockPrincipal;
   using (mocks.Record()) 
   {
      Expect.Call(mockPrincipal.IsInRole(Roles.ROLE_MAN_PERSON)).Return(true);
      Expect.Call(mockIdentity.Name).Return("ju"); 
      Expect.Call(mockPrincipal.Identity).Return(mockIdentity);
   }
}


Answer 2:

下面是我用回测试用户(使用存根)的代码:

    [SetUp]
    public void Setup()
    {
        var identity = MockRepository.GenerateStub<IIdentity>();
        identity.Stub(p => p.Name).Return("TestUser").Repeat.Any();
        var principal = MockRepository.GenerateStub<IPrincipal>();
        principal.Stub(p => p.Identity).Return(identity).Repeat.Any();

        Thread.CurrentPrincipal = principal;
    }

我有在其他代码LINQ所以我使用了变量VAR型; 刚刚替补正确的类型,如果需要(的IPrincipal,IIdentity的)。



文章来源: Mock IIdentity and IPrincipal