gpt4 book ai didi

c# - NSubstitute:模拟属性

转载 作者:行者123 更新时间:2023-11-30 17:29:15 25 4
gpt4 key购买 nike

我在单元测试中创建了 PersonAddressBook 类的替代品。AddressBook 类包含 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 属性返回 Person 实现而不是 IPerson 接口(interface),因此您返回 IPerson 的尝试将不工作。

模拟Person

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

或者返回一个实际的实例。

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

关于c# - NSubstitute:模拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51401316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com