c# - 如何模拟一个只读属性,其值取决于 Mock 的另一个属性

标签 c# .net moq

(如标签所示,我使用的是最小起订量)。

我有一个这样的界面:

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/

相关文章:

c# - 强制应用程序连续运行的保证方式(覆盖 taskkill、任务管理器等)

.net - String.Format 与否?

c# - 如何在不丢失 cookie 的情况下刷新我的 Selenium ChromeDriver 实例?

c# - 建议在对象构造函数中添加事件

.net - 如何比较两个字符串列表以找到相同的字符串

c# - 单元测试中的重复代码

c# - 将 AutoFixture 与最小起订量一起使用?

entity-framework - 模拟 DbFunctions.Like

c# - 提高此文本处理代码的效率

c# - Xamarin Forms OAuth 2.0 和 Azure Active Directory - 错误 AdalServiceException : AADSTS7000218