c# - 如何使用 NUnit 模拟属性?

标签 c# .net nunit mocking

如何使用 NUnit 模拟属性?


注意:我找到了this peripheral mocking answer非常有用,并将其重新用作此处的独特问答条目,供其他人查找。

也欢迎其他答案。

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)

最佳答案

在以下示例中模拟 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 中,PropertyName 可以使用模拟库的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


等等

This blog post考虑到 NUnit 似乎只为目标方法提供模拟方法,提供了额外的见解:

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

关于c# - 如何使用 NUnit 模拟属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331412/

相关文章:

c# - 如何在 NUnit 3.2 中创建全局初始化?

c# - 错误 CS1014 : A get or set accessor expected

c# - 使用win api模拟鼠标点击魔兽争霸3按钮

c# - 类型 'DateTime' 是在未引用的程序集中定义的?

c# - 为什么在使用 TestCaseSource 时 nUnit 测试会被忽略?

c# - 与 Throws<T> 方法类似的通用 DoesNotThrow<T> 方法在哪里?

C# 登录页面。 SQL 数据库路径

c# - Xamarin ios : ABAddressbook. 创建始终为空,无法请求访问

c# - 不同系列之间的堆叠条形边框

.net - 我应该为 .NET 中的 BigInt 类使用什么?