RhinoMocks: Correct way to mock property getter

前端 未结 3 1394
傲寒
傲寒 2021-02-13 21:30

I\'m new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.

I have a user object, we\'ll call it User, which has a p

3条回答
  •  误落风尘
    2021-02-13 22:11

    One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this:

    public class FakeUserType: User
    {
        //overriding code here
    }
    

    Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type.

    As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as aaronjensen mentioned as follows:

    public class User
    {
        public virtual Boolean IsAdministrator { get; set; }
    }
    

    This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior.

    Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this:

    public interface IUser
    {
        Boolean IsAdministrator { get; }
    }
    
    public class User : IUser
    {
        private UserSecurity _userSecurity = new UserSecurity();
    
        public Boolean IsAdministrator
        {
            get { return _userSecurity.HasAccess("AdminPermissions"); }
        }
    }
    
    public void CreateSomethingIfUserHasAdminPermissions()
    {
        IUser user = _mocks.StrictMock();
        SetupResult.For(user.IsAdministrator).Return(true);
    
        // do something with my User object
    }
    

    You can get fancier if you want by using dependency injection and IOC but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway.

    I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.

提交回复
热议问题