Search code examples
c#rhino-mocks

Stubbing Method with Base Class Type Parameter in Rhino Mocks


I'm trying to stub out a mock with a base class parameter, and have it return the same value for every call. I can't seem to get it to work correctly, and I can't get the wording correct on Google.

Basic data structures

public abstract class Base { }

public class BaseImplA : Base { } 
public class BaseImplB : Base { } 

public interface IDoStuff 
{ 
  bool DoStuff(Base b); 
}

Implementation:

var MockDoStuff = MockRepository.GenerateMock<IDoStuff>();

MockDoStuff.Stub(x => x.DoStuff<Arg<Base>.Is.TypeOf);
           .Return(true);

The stub isn't returning true because it's type checking to BaseImpl instead of Base.

What do I need to change to get it to accept Base rather than adding stubs for each of my BaseImpl-esque types?


Solution

  • There are syntax errors in your sample implementation code. Furthermore, in order to set a concrete method of a Mock to return a value, the target method must be marked Virtual or Override.

    Here is code that should work as desired:

    public abstract class Base { }
    
    public class BaseImplA : Base { }
    public class BaseImplB : Base { }
    
    public class IDoStuff
    {
        public virtual bool DoStuff(Base b)
        {
            return true;
        }
    } 
    

    Implementation

    public void TestMethod1()
    {
        var mockDoStuff = MockRepository.GenerateMock<IDoStuff>();
    
        mockDoStuff.Stub(x => x.DoStuff(Arg<Base>.Is.Anything)).Return(true);
    
        Assert.IsTrue(mockDoStuff.DoStuff(new BaseImplA()));
    }