简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM