NSubstitute: Mocking properties

I created substitutes for Person and AddressBook classes in the unit Test. The AddressBook class contains properties of type Person and name: SamplePerson.

public interface IAddressBook
{
    Person SamplePerson { get; set; }
}

public class AddressBook : IAddressBook
{
    public Person SamplePerson { get; set; }

    public AddressBook(Person samplePerson)
    {
        SamplePerson = samplePerson;
    }
}

public interface IPerson
{
    string GetName(string name);
}

public class Person : IPerson
{
    public string GetName(string name)
    {
        return name;
    }
}

public void TestMethod1()
{
    var personMock = Substitute.For<IPerson>();
    var addressBookMock = Substitute.For<IAddressBook>();

    addressBookMock.SamplePerson.Returns(personMock); //not working
    addressBookMock.SamplePerson = personMock; //not working
    addressBookMock.SamplePerson = (Person)personMock; //not working

    Assert.AreEqual(1, 1);
}

I would like to assign mock variable of Person type to propeties of mock variable of type AddressBook.

Is this possible?

1 answer

  • answered 2018-07-18 12:18 Nkosi

    IAddressBook.SamplePerson property returns Person implementation and not IPerson interface, so your attempt to return IPerson will not work.

    Either mock the Person class

    var personMock = Substitute.For<Person>();
    var addressBookMock = Substitute.For<IAddressBook>();
    addressBookMock.SamplePerson.Returns(personMock);
    

    or return an actual instance.

    var person = new Person();
    var addressBookMock = Substitute.For<IAddressBook>();
    addressBookMock.SamplePerson.Returns(person);