(如标签所示,我使用的是最小起订量)。
我有一个这样的界面:
interface ISource
{
string Name { get; set; }
int Id { get; set; }
}
interface IExample
{
string Name { get; }
ISource Source { get; set; }
}
在我的应用程序中,IExample 的具体实例接受 DTO (IDataTransferObject) 作为源。 IExample 的具体实现的一些属性只是委托(delegate)给 Source。像这样...
class Example : IExample
{
IDataTransferObject Source { get; set; }
string Name { get { return _data.Name; } }
}
我想创建一个独立的 IExample 模拟(独立意味着我不能使用捕获的变量,因为在测试过程中将创建多个 IExample 模拟实例)并设置模拟使得 IExample.Name 返回IExample.Source.Name 的值。所以,我想创建一个像这样的模拟:
var example = new Mock<IExample>();
example.SetupProperty(ex => ex.Source);
example.SetupGet(ex => ex.Name).Returns(what can I put here to return ex.Source.Name);
本质上,我想将模拟配置为返回模拟的子对象的属性值作为一个属性的值。
谢谢。
最佳答案
你可能会使用:
example.SetupGet(ex => ex.Name).Returns(() => example.Object.Source.Name);
然后将在访问属性时确定要返回的值,并将从模拟的 Source
属性的 Name
属性中获取。
关于c# - 如何模拟一个只读属性,其值取决于 Mock 的另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11545541/