19

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.

scher
  • 1,813
  • 2
  • 18
  • 39
  • For reference, the documentation mentioned in the question is [here](http://nsubstitute.github.io/help/partial-subs/). – David Tchepak Jul 05 '16 at 22:53
  • Note that the linked docs suggest avoiding the use of partial substitutes whenever possible. "WARNING: Partial substitutes will be calling your class’ real code by default, so if you are not careful it is possible for this code to run even while you are configuring specific methods to be substituted!" – sonnyb Jul 18 '19 at 21:02

1 Answers1

35

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.

Pawel Maga
  • 5,428
  • 3
  • 38
  • 62