使用Moq模拟与函数内部数据源的连接?

时间:2009-05-28 16:58:15

标签: c# unit-testing moq

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

我有以下课程:

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_source m_dest ,之后我想测试发送到 m_dest 的结果。

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

感谢。

3 个答案:

答案 0 :(得分: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 */);

}

答案 1 :(得分:2)

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

如果它们只是由一个setter或属性设置,则它就像:

一样简单
// 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

答案 2 :(得分: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));