c# - 模拟对象的属性以返回来自对象本身的值

标签 c# mocking moq

我想创建一个模拟,其中一个对象为一个属性返回一个来自同一模拟实例的另一个属性的值,但我不知道如何使用 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/

相关文章:

c# - 改善可感知的 WPF 应用程序启动时间

c# - 如何从 Vita 的后触摸板获取输入数据?

c# - 将文件移动到文件夹但忽略某些文件

c# - Ejabberd 模仿

node.js - 如何在没有 --bare 的情况下使用 Coffeescript 在 node.js 中 stub "global"模块变量?

java - 使用 Spring Boot 模拟配置不会获取属性文件

c# - 模拟方法结果

c# - Moq - 尝试测试 ActionResult 时出现空引用异常

c# - 模拟私有(private)领域

c# - 如何使用 Moq 模拟 HttpRequestMessage