如何使用 NUnit 模拟属性?

发布于 2024-10-23 22:25:23 字数 627 浏览 1 评论 0原文

如何使用 NUnit 模拟属性?


注意:我发现这个外围模拟答案非常有用,并将其重新用作此处的一个独特的问答条目,供其他人查找。

也欢迎其他答案。

NUnit-讨论注意事项: NUnit Mocks 是在一个周末创建的 作为一个玩具模拟实现[...]我开始认为这是一个错误,因为你还很远 从第一个开始依赖它的人开始。
-- http://groups.google.com/group/nunit-discuss/味精/55f5e59094e536dc
(NUnit 模拟中的 Charlie Pool)

How do I mock a property using NUnit?


NOTE: I found this peripheral mocking answer to be extremely useful and repurposed it as a distinct question and answer entry here for others to find.

Other answers welcome too.

NUnit-Discuss Note:
NUnit Mocks was created over a weekend
as a toy mock implementation [...] I'm beginning to think that was a mistake, because you are far
from the first person to become reliant on it.

-- http://groups.google.com/group/nunit-discuss/msg/55f5e59094e536dc
(Charlie Pool on NUnit Mocks)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

思慕 2024-10-30 22:25:23

要模拟以下示例中的 Names 属性...

Interface IView {    
    List<string> Names {get; set;} 
}

public class Presenter {    
    public List<string> GetNames(IView view)    {
       return view.Names;    
    } 
}

NUnit 属性的模拟解决方案

using NUnit.Mocks;

在 NUnit 中,可以使用 get_PropertyName 来模拟 PropertyName 来模拟get 访问器和 set_PropertyName 来模拟 set 访问器,使用模拟库的 Expect*(..) 方法,如下所示:

List names = new List {"Test", "Test1"};
DynamicMock mockView = new DynamicMock(typeof(IView));

mockView.ExpectAndReturn("get_Names", names);

IView view = (IView)mockView.MockInstance;
Assert.AreEqual(names, presenter.GetNames(view));

因此,在顶部的特定代码示例中, .Names 属性被模拟为 get_Namesset_Names


等等

这篇博文提供了额外的见解,考虑到 NUnit 似乎只提供了目标模拟方法方法:

我开始思考这个问题
意识到 Property getters 和
setter 只是被特殊对待
幕后的命名方法

To mock the Names property in the following example...

Interface IView {    
    List<string> Names {get; set;} 
}

public class Presenter {    
    public List<string> GetNames(IView view)    {
       return view.Names;    
    } 
}

NUnit Mock Solution for a Property

using NUnit.Mocks;

In NUnit a PropertyName can be mocked with get_PropertyName to mock the get accessor and set_PropertyName to mock the set accessor, using the mock library's Expect*(..) methods like so:

List names = new List {"Test", "Test1"};
DynamicMock mockView = new DynamicMock(typeof(IView));

mockView.ExpectAndReturn("get_Names", names);

IView view = (IView)mockView.MockInstance;
Assert.AreEqual(names, presenter.GetNames(view));

Therefore, in our specific code sample at the top, the .Names property is mocked as either get_Names or set_Names.


Etc.

This blog post provides additional insight considering NUnit seemingly provides mock methods to only target methods:

I started thinking about it and
realized that Property getters and
setters are just treated as speciallly
named methods under the covers

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