Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up Moq to ignore a virtual method

Tags:

c#

mocking

moq

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.

like image 303
moribvndvs Avatar asked Mar 04 '10 00:03

moribvndvs


1 Answers

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

like image 60
Pete Avatar answered Oct 22 '22 04:10

Pete