使用 Moq 函数语法设置非公共属性
有人知道 Moq 函数语法是否支持非公共属性的设置吗?我注意到它不起作用。
注意:这是针对函数语法的。
public class Foo
{
public virtual int FooProperty { get; protected set; }
}
这不会引发错误,但无法模拟 FooProperty
Mock.Of<Foo>(x => x.FooProperty == 1);
常规语法工作正常。
var mockFoo = new Mock<Foo>(); mockFoo.SetupGet(x=>x.FooProperty)
.Returns(1)
Anyone know if the Moq functional syntax supports setups for Non-Public properties? I noticed that it doesn't work.
NOTE: This is for the functional syntax.
public class Foo
{
public virtual int FooProperty { get; protected set; }
}
This doesn't throw an error, but fails to mock FooProperty
Mock.Of<Foo>(x => x.FooProperty == 1);
The regular syntax works fine.
var mockFoo = new Mock<Foo>(); mockFoo.SetupGet(x=>x.FooProperty)
.Returns(1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
微软研究院的 Pex/Moles 工具可能值得一看。 Moles 用于创建非公开内容的访问器。
It might be worth looking at the Pex/Moles tool from Microsoft Research. Moles is used to create accessors for non-public stuff.
如果您向包含被测类的程序集添加程序集属性(添加到 AssemblyInfo.cs),它将支持模拟内部属性:(
当然,您还必须为您的测试项目添加一个 InternalsVisibleTo 条目。)
如果您执行此操作后,您可以模拟添加此属性的程序集中的任何内部属性。如果您想模拟私有或受保护的属性,我很确定没有办法直接做到这一点。如果它们受到保护,您可以创建一个虚拟继承者并为其提供访问/操作其受保护成员的公共方法或属性。对于私人来说,我相信你真的无能为力。
It will support mocking of internal properties if you add an assembly attribute to the assembly containing the class under test (add to AssemblyInfo.cs):
(You would also have to add an InternalsVisibleTo entry for your test project, of course.)
If you do this, you can mock any internal property in the assembly to which this is added. If you want to mock private or protected properties, I'm pretty sure there's no way to do that directly. If they're protected, you could create a Dummy inheritor and give it public methods or properties that access/manipulate its protected members. For private, there's really nothing you can do, I believe.