当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - NSubstitute: Difference between Substitute.For<> and Substitute.ForPartsOf

问题描述:

I'm using NSubstitute. I have to fake a class and cannot dig out the difference of Substitute.For<...>() and Substitute.ForPartsOf<...>. I already read the documentation but don`t get the point, where the two behave different.

网友答案:

Substitute.For<>() creates full mock, while Substitute.ForPartsOf<> creates partial mock. For example:

[Test]
public void Test()
{
    var person = Substitute.For<Person>();
    person.GetAge().Returns(20);
    var age = person.GetAge(); //returns 20
    var name = person.GetName(); //returns empty string

    var partialPerson = Substitute.ForPartsOf<Person>();
    partialPerson.GetAge().Returns(20);
    var age2 = partialPerson.GetAge(); //returns 20
    var name2 = partialPerson.GetName(); //returns John
}

public class Person
{
    public string Name { get; } = "John";
    public int Age { get; } = 10;

    public virtual int GetAge()
    {
        return Age;
    }

    public virtual string GetName()
    {
        return Name;
    }
}

Generally ForPartsOf<> will use concrete implementation if it has not been substituted.

分享给朋友:
您可能感兴趣的文章:
随机阅读: