2

我开始使用 Moq,但我无法弄清楚如何在下面的代码中测试Execute方法:

我有以下课程:

public class MyObject {
    private IDataReaderPlugin m_source;
    private IDataWriterPlugin m_dest;
    private string[] m_dummyTags = new string[] { "tag1", "tag2", "tag3"};

    public void Execute(DateTime time)
    {
        DataCollection tags = m_source.SnapshotUtc(m_dummyTags, time);

        //Doing some treatment on the values in tags    

        m_dest.Write(tags); 
    }

}

另一种方法负责根据配置文件中的信息创建和初始化 IDataReaderPlugin 和 IDataWriterPlugin。

我想测试 Execute 方法。所以,我需要模拟m_sourcem_dest,然后我想测试发送到m_dest的结果。

我如何通过 Moq 实现这一目标?

谢谢。

4

3 回答 3

4
[Test]
public void ShouldWriteToMDest()
{
   // Arrange
   var mockDest = new Mock<IDataWriterPlugin>();
   var mockSource = new Mock<IDataReaderPlugin>();
   string[] m_dummyTags = new string[] { "tag1", "tag2", "tag3"};

   mockSource.Setup(source => source.SnapshotUtc(m_dummyTags, It.IsAny<DateTime>()).Returns(/*whatever you need*/);

   var myObj = new MyObject(mockSource.Object, mockDest.Object);

   // Act
   myObj.Execute(DateTime.Now);


   // Assert
   Assert.That(mockSource.Object.WhateverPropertyContainsOutput == /*Whatever you need */);

}
于 2009-05-28T17:23:04.987 回答
2

“另一种方法是负责任的” - 这是关键的信息。如果您使用的是 IoC 或 DI 框架,那么您需要插入一些接口的 Moq 模拟IDataReaderPluginIDataWriterPlugin. 然后该Execute方法将使用 IoC/DI 框架提供的这些模拟。

如果它们只是由设置器或属性设置,那么它很简单:

// Arrange
var mo = new MyObject();
var srcMock = new Mock<IDataReaderPlugin>();
src.Setup(src => src.SnapshotUtc(It.IsAny<string[]>(), It.IsAny<DateTime>()))
   .Returns(new DataCollection() /* or whatever */);
mo.SetSource(srcMock.Object);
// ... same for m_dest
// Act
mo.Execute(DateTime.Now);
// Assert
// assert something... srcMock.Verify() or whatever
于 2009-05-28T17:21:09.233 回答
2

这应该让你开始:

DateTime myDate = DateTime.Now;

DataCollection tags = new DataCollection();

Mock<IDataReaderPlugin> dataReaderPlugin = new Mock<IDataWriterPlugin>();
dataReaderPlugin.Setup(drp => drp.SnapshotUtc(It.IsAny<string[]>(), myDate)).Returns(tags);

Mock<IDataWriterPlugin> dataWriterPlugin = new Mock<IDataWriterPlugin>();
dataWriterPlugin.Setup(dwp => dwp.Write(tags);    

MyObject mo = new MyObject();
mo.Execute();

mock.Verify(foo => foo.Write(tags));
于 2009-05-28T17:23:04.113 回答