基于现有的实例创建模拟

时间:2015-06-10 06:26:18

标签: mocking moq

我正在使用Moq。是否可以基于现有的实例创建模拟对象? 我的类有一点复杂的初始化,它从外部xml文件加载一些信息。我已经有了一些例程来进行初始化,并且很容易获得一个现有的对象。我想如果Moq可以从这个现有实例中创建一个模拟对象,并且除了设置调用之外通常会调用实例。我知道我可以通过将CallBase设置为true来获取模拟对象,但我需要在模拟对象上进行许多初始化。这是我的希望:

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();

如果可能的话,感谢您的任何想法。

1 个答案:

答案 0 :(得分:0)

这是一个例子。请注意,您需要将您要模拟的方法标记为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"
 }