Writing Methods To Minimize Mocking Code

I was using TypeMock to mock some test code, and I was contemplating the setup.  I have a method, which is going to instantiate an object.  This static object calls some configuration code to setup itself with data, which I could mock to return a specific subset of data.  This was going to be a lot of code, because I could mock the configuration code, which pre-defines the content that's available within this instantiated object, which my component that I originally was testing was going to call.  So it would be something like this:

public void MyMethod()
{
     var obj = ConfigObject.GetInstance();
}

and GetInstance looks like:

public static ConfigObject GetInstance()
{
    ConfigSection section = (ConfigSection)ConfigurationManager.GetSection("..");
    //pass information to object
}

Now, ConfigObject has a lot of information, so it's not like I'd be only working with a few props, but many collections and configuration is a pain.  I circumvented all of this with a private method that does:

private object GetConfigValue(..)
{
   //Instantiates ConfigSection, gets the value desired, and returns it
}

This way, GetConfigValue() does the actual work, and I can change my code to simply mock thsi one method.  I can do this by:

Mock mock = MockManager.Mock<ConsumingObject>();
mock.ExpectAndReturn("GetConfigValue", 123);

And thus, my TypeMock mock now is reduced to one line of code.  TypeMock mocks GetConfigValue, which means this method isn't called, but the value 123 is returned in its stead.  Pretty cool.

Comments

No Comments