Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute: Difference between Substitute.For<> and Substitute.ForPartsOf

Tags:

c#

nsubstitute

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.

like image 311
scher Avatar asked Jul 05 '16 09:07

scher


1 Answers

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.

like image 189
Pawel Maga Avatar answered Nov 01 '22 03:11

Pawel Maga