如何使用 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_Names 或 set_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/