【问题标题】:how to mock a property with private setter using NSubstitute如何使用 NSubstitute 使用私有设置器模拟属性
【发布时间】:2015-03-21 21:29:22
【问题描述】:

我有一个带有属性“数据”的类“示例”,它有一个私有设置器,我想模拟该数据属性

Public class Example { public string data {get; private set;}}

我想使用 NSubstitute 模拟数据属性。有人可以帮我怎么做。

【问题讨论】:

  • 可能不可能 - 大多数模拟库无法模拟非虚拟、非接口方法。除了重新设计你的类,你需要一些更重的工具来重写代码,比如Microsoft Moles
  • 您是否能够编辑Example 类可能值得注意。正如@AlexeiLevenkov 所指出的,如果您不能,那么 NSub 将无法帮助您。如果可以的话,@JohnKoerner 的回答显示了一种方法。
  • 将 getter 过程放在 virtual 方法中,然后对其进行模拟。

标签: c# private nsubstitute


【解决方案1】:

NSubstitute 只能模拟具体类上的 abstractvirtual 方法。如果您可以修改底层代码以使用接口,那么您可以模拟接口:

public class Example : IExample { public string data { get; private set; } }
public interface IExample { string data { get; } }

[TestMethod]
public void One()
{
    var fakeExample = NSubstitute.Substitute.For<IExample>();
    fakeExample.data.Returns("FooBar");

    Assert.AreEqual("FooBar", fakeExample.data);
}

【讨论】:

  • 使Example.data 虚拟化也适用于此测试,无需添加接口。 (虽然我通常更喜欢基于动态代理的模拟接口。)
  • 听起来是对的,但我已经能够在 Method 不是抽象或虚拟的地方使用替代品.Received(1).Method()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多