How should I mock this abstract class with Moq?

This is not really specific to Moq but more of a general Mocking framework question. I have created a mock object for an object of type, "IAsset". I would like to mock the type that is returned from IAsset 's getter, "Info".

 var mock = new Mock<IAsset>();
        mock.SetupGet(i => i.Info).Returns(//want to pass back a mocked abstract);
        mock.SetupProperty(g => g.Id, Guid.NewGuid());

The problem I am running into is Mocking this returned property value.

 mock.SetupGet(i => i.Info).Returns(//this is the type I need to mock);

The property holds an abstract type. This type extends XDocument.

public abstract class SerializableNodeTree : XDocument, ISerializable{...}

So.. what I would like to do is this:

 var nodeTreeMock = new Mock<SerializableNodeTree>();
        nodeTreeMock .SetupGet(d => d.Document).Returns(xdoc);

xdoc is a XDocument instance. This will not work because the XDocument.Document getter is not virtual. Which makes sense.

Should I just hand code a mock that is derived from SerializableNodeTree or is this there a way to Mock this object?


In a case like this, I would treat XDocument as a standard, non-mockable object like string s and most POCOs and native types. That is to say, you should create a real (non-mocked) SerializableNodeTree to return from IAsset.Info .

Another option is to make SerializableNodeTree implement an interface that has all the methods you want to mock, and have IAsset.Info return that interface type instead of a SerializableNodeTree directly.


In this case I would create a test double that derives from your abstract class. That'll give you what you need in your test.

public class SerializableNodeTreeDouble : SerializableNodeTree
{
   public new XDocument Document
   {
     get;         
     set;
   }

   ...
}

public void TestMethod()
{
   SerializableNodeTreeDouble testDouble = new SerializableNodeTreeDouble();
   testDouble.XDocument = xdoc; // your xdoc

   ...
}

Hope this helps.

链接地址: http://www.djcxy.com/p/54058.html

上一篇: 嘲笑使用Moq实现IQueryable的类

下一篇: 我应该如何用Moq来嘲笑这个抽象类?