Create mock based on existed real instance

279 views Asked by At

I'm using Moq. Is it possible to create a mock object based on an existed real instance? My class has a little complex as initialization which load some info from an external xml file. I already had some routines to make this initialization and can easily to get an existed object. I think if Moq can make a mock object from this existed instance and usually make calls to the real instance except I setup the calls. I know I can get a mock object by setting CallBase to true, but I need to make many initializations on the mock object. Here is what I hope:

MyClass myclass = GetMyClass();
var mock = Mock.Get<MyClass>(myclass); // This will raise exception because myclass is not a mock object
mock.SetUp<String>(p=>p.SomeMethod).Returns("Test String"); // Only SomeMethod() should be mocked

// this will call SomeMethod and get the test string, for other methods that are not mocked will do the real calls
myclass.DoRealJob();

Thanks for any idea if possible.

1

There are 1 answers

2
Padraic On

Here is an example. Note you will need to mark your method that you're going to mock as virtual.

public class MyClass
{
    public virtual string SomeMethod()
    {
            return "real";
    }
}

 [Test]
 public void TestingSO()
 {
     var myMockClass = new Mock<MyClass>();

     myMockClass.Setup(c => c.SomeMethod()).Returns("Moq");

     var s = myMockClass.Object.SomeMethod(); //This will return "Moq" instead of "Real"
 }