我上课
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.
答案 0 :(得分:0)
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;
}