moribvndvs
moribvndvs

Reputation: 42497

Setting up Moq to ignore a virtual method

I have an abstract class that has a virtual method. The method is virtual in the event that a later implementation needs to override that functionality.

However, Moq proxies all virtual methods so I don't seem to be able to test the actual code that's written, and instead uses the Mock setup for that method (which is currently to return the default value).

Example abstract:

public abstract SomeAbstract
{
    public abstract Format(IFormatProvider provider, string format)
    {
          // does some stuff i need to test
    }
}

My NUnit test:

[Test]
public void Should_Set_Format_State()
{
   Mock<SomeAbstract> mock = new Mock<SomeAbstract>();
   mock.Object.Format(CultureInfo.CurrentCulture, "format string");

   // do tests to make sure Format correctly changed the object's state
}

How do I set up my Mock object to just let my virtual Format method work, without having to remove virtual from the method?! Perhaps I'm abusing the mocking concept in this case.

Upvotes: 10

Views: 4277

Answers (1)

Pete
Pete

Reputation: 11505

I believe setting "CallBase = true" on the mock will work. See the "Customizing Mock Behavior" section of the Quick Start

Upvotes: 16

Related Questions