1

我在编写单元测试时遇到了一个问题,在我调用它的方法中,它不会修改我传入的模拟对象。我不确定我是否缺少明显的东西?

我将模拟设置如下:

var mockList = new List<Mock<IDocument>>();

for (int i = 0; i < 4; i++)
{
    var mockDocument = new Mock<IDocument>();
        mockDocument.Setup(t => t.DocumentNo).Returns(i.ToString()); 
        mockList.Add(mockDocument);
}

mockDocumentRepository.Setup(x => x.GetDocuments(It.IsAny<string>(), It.IsAny<string>()))
    .Returns(mockList.Select(m => m.Object).ToList());

在执行的方法中,如果我尝试修改模拟类的另一个属性(例如 t.DocumentName),则值保持不变Null。无论如何设置该属性以接受修改?

我这样做的原因是测试文档集合是否已被方法中的另一个集合修改。不确定是否有更好的方法来做到这一点?

4

1 回答 1

3

Moq will leave all methods unimplemented unless instructed to do otherwise, and that includes properties. If you use mockDocument.SetupProperty(doc => doc.DocumentName); it will implement the property as a regular auto-property. You can use mockDocument.SetupAllProperties() if you want all properties to be auto-implemented, but you'll still have to do it for every mock object.

You could also consider making a stub instead of a mock:

public class StubDocument : IDocument
{
    public string DocumentNo { get; set; }
    public string DocumentName { get; set; }
    ...
}

In general, I find that stubbing is often preferable to mocking when dealing with very simple interfaces, as seems to be the case with your IDocument.

于 2013-09-03T10:51:15.190 回答