c# - 无法初始化模拟类的成员

标签 c# unit-testing interface moq

我有一个有成员的接口(interface),像这样:

public interface IDataLoader
{
    //other stuff
    // tools for loading the items to be processed from disk or cloud
    CustomCollection ItemsToBeProcessed {get; set;}
}

我正在为使用这些 ItemsToBeProcessed 的系统的其他组件做 UT,我想避免加载的复杂性和依赖性。

在每个 UT 中,我想用特定的硬编码数据填充 ItemsToBeProcessed。然后将数据馈送到被测模块(处理器模块)并将输出与特定的硬编码预期数据进行比较。

我的问题是我无法初始化此 ItemsToBeProcessed 并且我不明白为什么。

到目前为止,这是我的 UT:

[Test]
public void DataProcessor_TestData1_asExpected()
{
    Mock<IDataLoader> mokedAmplifier = new Mock<IDataLoader>(MockBehavior.Loose);
    MainController.Loader = mokedAmplifier.Object;
    if(MainController.Loader.ItemsToBeProcessed == null)
        MainController.Loader.ItemsToBeProcessed = new CustomCollection();

    // here the MainController.Loader.ItemsToBeProcessed is still null.. why???

    var TestData = LoadTestData("testData1.xml");
    var ExpectedData = LoadExpectedData("ExpectedData1.xml")

    MainConroller.Loader.ItemsToBeProcessed.AddRange(TestData);

    var ProcessingModuleBeingTested = new ProcessingModule();
    var results = ProcessingModuleBeingTested.Process(MainController.Loader.ItemsToBeProcessed);
    Asert.isEqual(ExepctedData, results);
}

如何初始化这个成员?

最佳答案

模拟所需成员以在调用时返回可用对象。

var collection = new CustomCollection();
var mokedAmplifier = new Mock<IDataLoader>(MockBehavior.Loose);

mokedAmplifier.Setup(_ => _.ItemsToBeProcessed).Returns(collection);

//...

如果您希望模拟记住对属性所做的更改,请使用 SetupAllProperties

Specifies that the all properties on the mock should have "property behavior", meaning that setting its value will cause it to be saved and later returned when the property is requested. (this is also known as "stubbing"). The default value for each property will be the one generated as specified by the Moq.Mock.DefaultValue property for the mock.

var mokedAmplifier = new Mock<IDataLoader>(MockBehavior.Loose);

mokedAmplifier.SetupAllProperties(); //<--

MainController.Loader = mokedAmplifier.Object;

if(MainController.Loader.ItemsToBeProcessed == null)
    MainController.Loader.ItemsToBeProcessed = new CustomCollection();

//...

引用 Moq Quickstart获得理解模拟框架的帮助。

关于c# - 无法初始化模拟类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54194974/

相关文章:

java - 在面向对象编程中,在其方法中引用接口(interface)子项是正确的方法吗?

c# - 如何过滤 Telerik 的 RadGrid 的 GridTemplateColumns

c# - 在不同线程中创建的控件.NET

c# - 重置下拉值

c++ - 回归测试如何证明是否调用了 VirtualAlloc?

c++ - 我尝试用 googlemock 模拟一个简单的 C++ 方法有什么问题?

interface - C++/CLI : Cannot explicitly implement interface member with different return type

c# - C# 中的非 volatile 对象

c# - 使用 Moq 的 ElasticClient 的代码覆盖率

oop - 每个单独的对象都应该有一个接口(interface)并且所有对象都松散耦合吗?