NSubstitute:模拟属性
NSubstitute: Mocking properties
我在单元测试中创建了 Person
和 AddressBook
class 的替代品。
AddressBook
class 包含类型 Person
和名称的属性: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);
}
我想将 Person
类型的模拟变量分配给 AddressBook
.
类型的模拟变量的 propeties
这可能吗?
IAddressBook.SamplePerson
属性 returns Person
实现而不是 IPerson
接口,所以你尝试 return IPerson
不会工作。
要么模拟 Person
class
var personMock = Substitute.For<Person>();
var addressBookMock = Substitute.For<IAddressBook>();
addressBookMock.SamplePerson.Returns(personMock);
或return实际实例。
var person = new Person();
var addressBookMock = Substitute.For<IAddressBook>();
addressBookMock.SamplePerson.Returns(person);
我在单元测试中创建了 Person
和 AddressBook
class 的替代品。
AddressBook
class 包含类型 Person
和名称的属性: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);
}
我想将 Person
类型的模拟变量分配给 AddressBook
.
这可能吗?
IAddressBook.SamplePerson
属性 returns Person
实现而不是 IPerson
接口,所以你尝试 return IPerson
不会工作。
要么模拟 Person
class
var personMock = Substitute.For<Person>();
var addressBookMock = Substitute.For<IAddressBook>();
addressBookMock.SamplePerson.Returns(personMock);
或return实际实例。
var person = new Person();
var addressBookMock = Substitute.For<IAddressBook>();
addressBookMock.SamplePerson.Returns(person);