C# 在 Returns() 中组装值时访问 Expect() 的原始参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/578653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing the original arguments of Expect() when assembling the value in Returns()
提问by patridge
Is it possible to get access to the parameter used to make a call to a mocked expectation when assembling the Returns object?
在组装 Returns 对象时,是否可以访问用于调用模拟期望的参数?
Here is a stub for the objects involved and, given that, I am trying to mock a Collection:
这是所涉及对象的存根,鉴于此,我正在尝试模拟一个集合:
Class CollectionValue {
public Id { get; set; }
}
Class Collection {
private List<CollectionValue> AllValues { get; set; }
public List<CollectionValue> GetById(List<int> ids) {
return AllValues.Where(v => ids.Contains(v.Id));
}
}
Given a test list of CollectionValues that will be used for the mocked object, how does one go about setting up an expectation that will handle every possible permutation of the IDs in that list of CollectionValues, including calls that combine existing IDs and non-existing IDs? My problem comes from a desire to set up all possible expectations in a single call; if access to the original parameter isn't possible, I could just as easily set up just the exact expectation I want to test in a given call each time.
给定将用于模拟对象的 CollectionValues 测试列表,如何设置预期以处理该 CollectionValues 列表中 ID 的所有可能排列,包括组合现有 ID 和不存在 ID 的调用? 我的问题来自于希望在一次调用中设置所有可能的期望;如果无法访问原始参数,我可以轻松地设置我每次在给定调用中要测试的确切期望值。
Here is what I was hoping to do, where "???" represents where it would be handy to have access to the parameter used to call GetById (the one that qualified the It.IsAny restriction):
这是我希望做的,“???” 表示可以方便地访问用于调用 GetById 的参数(限定 It.IsAny 限制的参数):
CollectionMock.Expect(c => c.GetById(It.IsAny<List<int>>())).Returns(???);
采纳答案by BenA
From the moq quickstartguide:
从最小起订量快速入门指南:
// access invocation arguments when returning a value
mock.Setup(x => x.Execute(It.IsAny<string>()))
.Returns((string s) => s.ToLower());
Which suggests therefore that you can fill in your ??? as
因此,这表明您可以填写您的 ??? 作为
CollectionMock.Expect(c => c.GetById(It.IsAny<List<int>>()))
.Returns((List<int> l) => //Do some stuff with l
);