Rhino mock an abstract class w/o mocking its virtual method?

前端 未结 2 836
孤独总比滥情好
孤独总比滥情好 2021-01-13 00:18

Can I execute the body of a virtual method that lives on an abstract class which has been mocked using Rhino Mocks?

To be clear, I\'m not trying to mock the behavior

2条回答
  •  天涯浪人
    2021-01-13 00:46

    Yes, that should be absolutely fine. I can't say I've tried it, but I'd be very surprised if it failed.

    EDIT: I suspect you want the PartialMock method. Here's an example:

    using System;
    using Rhino.Mocks;
    
    public abstract class Abstract
    {
        public virtual int Foo()
        {
            return Bar() * 2;
        }
    
        public abstract int Bar();        
    }
    
    class Test
    {
        static void Main(string[] args)
        {
            MockRepository repository = new MockRepository();
            Abstract mock = repository.PartialMock();
    
            using (repository.Record())
            {
                Expect.Call(mock.Bar()).Return(5);
            }
    
            Console.WriteLine(mock.Foo()); // Prints 10
        }
    }
    

    EDIT: Or in my first attempt at AAA:

    using System;
    using Rhino.Mocks;
    
    public abstract class Abstract
    {
        public virtual int Foo()
        {
            return Bar() * 2;
        }
    
        public abstract int Bar();        
    }
    
    class Test
    {
        static void Main(string[] args)
        {
            // Arrange
            Abstract mock = MockRepository.GeneratePartialMock();
            mock.Stub(action => action.Bar()).Return(5);
    
            // Act
            int result = mock.Foo();
    
            // Assert
            mock.AssertWasCalled(x => x.Bar());
            // And assert that result is 10...
        }
    }
    

提交回复
热议问题