我想创建一个模拟,其中一个对象为一个属性返回一个来自同一模拟实例的另一个属性的值,但我不知道如何使用 Moq 进行设置。
我找到的所有 Setup/SetupGet 签名都允许仅返回常量值,而不是来自同一对象的值。
示例:
void Main()
{
var obj = GetMock().Object;
obj.PropA = "test";
Console.WriteLine(obj.Id); // Should return -354185609, as it's the result of "test".GetHashCode()
obj.PropA = "test 2";
Console.WriteLine(obj.Id); // Should return -1555281747, as it's the result of "test 2".GetHashCode()
}
public interface IMyObject
{
int Id { get;set;}
string PropA {get; set;}
}
public Mock<IMyObject> GetMock()
{
var objectMock = new Mock<IMyObject>();
objectMock.SetupAllProperties();
objectMock
.SetupGet((IMyObject s) => s.Id)
//Here I would like to write something like :
.Returns(s => (a.PropA?.GetHashCode()).GetValueOrDefault()));
// To have the Getter of Id initialized with the current value of PropA.GetHashCode()
return objectMock;
}
感谢您的建议
最佳答案
您可以使用Callback
来存储set
中的值,然后在Returns
中重用它。像这样的事情:
string propA = null;
var mock = new Mock<IMyObject>();
mock.SetupSet(m => m.PropA = It.IsAny<string>())
.Callback<string>(s => propA = s);
mock.Setup(m => m.Id)
.Returns(() => (propA?.GetHashCode()).GetValueOrDefault());
mock.Object.PropA = "test";
Assert.Equal("test".GetHashCode(), mock.Object.Id);
mock.Object.PropA = "test 2";
Assert.Equal("test 2".GetHashCode(), mock.Object.Id);
另一个选择是实际实现并使用CallBase
功能。 (类似于 answer )
public abstract class MyObjectDummy : IMyObject
{
public virtual int Id { get; set; }
public virtual string PropA { get; set; }
}
var mock = new Mock<MyObjectDummy>();
mock.SetupSet(m => m.PropA = It.IsAny<string>()).CallBase();
mock.SetupGet(m => m.PropA).CallBase();
mock.Setup(m => m.Id).Returns(() => (mock.Object.PropA?.GetHashCode()).GetValueOrDefault());
mock.Object.PropA = "test";
Assert.Equal("test".GetHashCode(), mock.Object.Id);
关于c# - 模拟对象的属性以返回来自对象本身的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953977/