gpt4 book ai didi

c# - 如何在 C# 中最小化 protected 属性

转载 作者:行者123 更新时间:2023-11-30 15:54:46 26 4
gpt4 key购买 nike

public class Business {  
protected List<BusinessRulesDto> BusinessRules { get; set; }
}

我试过:

  1. businessMockObject.Protected().SetupSet<List<BusinessRulesDto>>("BusinessRules", ItExpr.IsAny<List<BusinessRulesDto>>()).Verifiable();
  2. var businessRulesDtoList = Builder<BusinessRulesDto>.CreateListOfSize(2).Build().ToList();  
    businessMockObject.Protected().SetupGet<List<BusinessRulesDto>>("BusinessRules").Returns(businessRulesDtoList);
    businessMockObject.Protected().SetupSet<List<BusinessRulesDto>>("BusinessRules", ItExpr.IsAny<List<BusinessRulesDto>>()).Verifiable();

我尝试了很多事情,但都没有成功。我可以模拟 protected 方法,但不能模拟 protected 属性。

如何模拟 protected 属性?

最佳答案

根据 documentation

Moq 4.8 and later allows you to set up protected members through a completely unrelated type that has the same members and thus provides the type information necessary for IntelliSense to work. You can also use this interface to set up protected generic methods and those having by-ref parameters:

在测试项目中创建一个接口(interface),封装被mock的protected成员

public interface IBusinessProtectedMembers {  
List<BusinessRulesDto> BusinessRules { get; set; }
}

然后将其与 mock 一起使用以利用 IntelliSense

var businessRulesDtoList = Builder<BusinessRulesDto>.CreateListOfSize(2).Build().ToList();
businessMockObject.Protected().As<IBusinessProtectedMembers>()
.Setup(_ => _.BusinessRules)
.Returns(businessRulesDtoList);

最后,这一切都取决于 Moq 的要求,即要模拟/ stub 的成员必须是虚拟,以便允许框架覆盖成员。

这意味着业务应该是这样的

public class Business {  
protected virtual List<BusinessRulesDto> BusinessRules { get; set; }
}

上述建议可行。

关于c# - 如何在 C# 中最小化 protected 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com