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

半腔热情 提交于 2019-12-09 03:13:34

问题


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 of the virtual method. I'm trying to /test/ the virtual method (on the mocked class).

Is this idea a blatant misuse of Rhino Mocks?


回答1:


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<Abstract>();

        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<Abstract>();
        mock.Stub(action => action.Bar()).Return(5);

        // Act
        int result = mock.Foo();

        // Assert
        mock.AssertWasCalled(x => x.Bar());
        // And assert that result is 10...
    }
}



回答2:


You need to tell Rhino.Mocks to call back to the original implementation instead of doing its default behavior of just intercepting the call:

var mock = MockRepository.GenerateMock<YourClass>();
mock.Setup(m => m.Foo()).CallOriginalMethod(OriginalCallOptions.NoExpectation);

Now you can call the Foo() method on your mock object.



来源:https://stackoverflow.com/questions/6960459/rhino-mock-an-abstract-class-w-o-mocking-its-virtual-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!