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?
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.