如何模拟一个readonly属性,其值取决于模拟的另一个属性

wag*_*ghe 22 .net c# moq

(如标签所示,我使用的是moq).

我有这样的界面:

interface ISource
{
  string Name { get; set; }
  int Id { get; set; }
}

interface IExample
{
  string Name { get; }
  ISource Source { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,IExample的具体实例接受DTO(IDataTransferObject)作为Source.IExample的具体实现的一些属性只是委托给Source.像这样...

class Example : IExample
{
  IDataTransferObject Source { get; set; }

  string Name { get { return _data.Name; } }
}
Run Code Online (Sandbox Code Playgroud)

我想创建的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);
Run Code Online (Sandbox Code Playgroud)

本质上,我想配置mock作为一个属性的值,返回mock的子对象的属性值.

谢谢.

Iri*_*ium 43

你可以使用:

example.SetupGet(ex => ex.Name).Returns(() => example.Object.Source.Name);
Run Code Online (Sandbox Code Playgroud)

然后,在访问属性时将确定要返回的值,并将从Namemock的Source属性的属性中获取.