使用 Moq 函数语法设置非公共属性

发布于 2024-12-11 22:15:48 字数 415 浏览 0 评论 0原文

有人知道 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

⊕婉儿 2024-12-18 22:15:48

微软研究院的 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.

遥远的她 2024-12-18 22:15:48

如果您向包含被测类的程序集添加程序集属性(添加到 AssemblyInfo.cs),它将支持模拟内部属性:(

// This assembly is the default dynamic assembly generated Castle DynamicProxy, 
// used by Moq. Paste in a single line.
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

当然,您还必须为您的测试项目添加一个 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):

// This assembly is the default dynamic assembly generated Castle DynamicProxy, 
// used by Moq. Paste in a single line.
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文