【问题标题】:Mock a property with a private setter using NSubstitute使用 NSubstitute 使用私有设置器模拟属性
【发布时间】:2019-12-09 12:40:53
【问题描述】:

我有课

public class MyClass
{
   public int MyProperty1 { get; private set; }
   public int MyProperty2 { get; private set; }

   public MyClass(){}
   public MyClass(int myProperty2) => MyProperty2 = myProperty2;
}

在我的单元测试中,我需要在做出如下断言之前更改 MyProperty1 的值

[Fact]
public void MyTest()
{
   var fake = NSubstitute.Substitute.For<MyClass>(3);
   fake.MyProperty1.Returns(5);

   //Assertion
}

但是我得到了错误

Outcome: Failed
    Error Message:
    NSubstitute.Exceptions.CouldNotSetReturnDueToNoLastCallException : Could not find a call to return from.

【问题讨论】:

  • 这可能是XY problem。我的第一个问题是你为什么要这么做?你到底想测试什么?

标签: c# unit-testing .net-core mocking nsubstitute


【解决方案1】:

NSubstitute 可以not stub non-virtual members of classes(请参阅How NSubstitute Works 以获得解释)。我强烈建议将 NSubstitute.Analyzers 包添加到任何引用 NSubstitute 的测试项目中,因为这将在尝试替换非虚拟方法时提供编译时警告。

Property1 更新为virtual 后,测试按预期工作:

public class MyClass
{
    public virtual int MyProperty1 { get; private set; }
    public int MyProperty2 { get; private set; }

    public MyClass() { }
    public MyClass(int myProperty2) => MyProperty2 = myProperty2;
}

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多