我有一个有成员的接口(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/