Mock IIdentity and IPrincipal

前端 未结 2 630
故里飘歌
故里飘歌 2021-02-08 12:46

I just wanna ask what would be better approach to supply these objects in my unit tests.

In my unit test I am testing CSLA object. CSLA object is internally using one pr

2条回答
  •  一向
    一向 (楼主)
    2021-02-08 13:10

    The reason you're getting a null reference error is because IPrincipal.Identity is null; it hasn't been set in your mocked IPrincipal yet. Calling .Name the null Identity results in your exception.

    The answer, as Carlton pointed out, is to mock IIdentity also, and set it up to return "ju" for its Name property. Then you can tell IPrincipal.Identity to return the mock IIdentity.

    Here is an expansion of your code to do this (using Rhino Mocks rather than Stubs):

    public void BeforeTest()
    {
       mocks = new MockRepository();
       IPrincipal mockPrincipal = mocks.CreateMock();
       IIdentity mockIdentity = mocks.CreateMock();
       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);
       }
    }
    

提交回复
热议问题