使用 Moq 调用原始方法
我有一个具有 2 个方法的 ProductRepository:GetAllProducts 和 GetProductByType,我想测试 GetProductByType 的逻辑。在内部,GetProductByType 调用 GetAllProducts,然后筛选正确的产品。
public virtual IEnumerable<Product> GetAllProducts()
{
//returns all products in memory, db etc
}
public virtual IEnumerable<Product> GetProductsByType(string type)
{
return (from p in GetAllProducts() where p.Type == type select p).ToList();
}
因此,在我的测试中,我想模拟对 GetAllProducts 的调用,以便它返回在我的测试中定义的产品列表,然后调用原始的 GetProductsByType,这将消耗模拟的 GetAllProducts。
我正在尝试类似下面的代码,但原始的 GetProductByType 没有执行,它也是模拟的。在 TypeMock 中,我有一个 CallOriginal 方法可以解决这个问题,但我无法用 Moq 解决这个问题。有什么想法吗?
var mock = new Mock<ProductRepository>();
mock.Setup(r => r.GetAllProducts()).Returns(new List<Product>() {p1, p2, p3});
var result = mock.Object.GetProductsByType("Type1");
Assert.AreEqual(2, result.Count());
I have a ProductRepository with 2 methods, GetAllProducts and GetProductByType, and I want to test the logic at GetProductByType. Internally, GetProductByType makes a call to GetAllProducts and then filters the correct ones.
public virtual IEnumerable<Product> GetAllProducts()
{
//returns all products in memory, db etc
}
public virtual IEnumerable<Product> GetProductsByType(string type)
{
return (from p in GetAllProducts() where p.Type == type select p).ToList();
}
So in my test I'd like to mock the call to GetAllProducts, so it returns a list of products defined at my test, and then call the original GetProductsByType, which will consume the mocked GetAllProducts.
I'm trying something like the code below but the original GetProductByType is not executed, it is mocked-out as well. In TypeMock I have a CallOriginal method that fixes this, but I can't figure it out with Moq. Any ideas?
var mock = new Mock<ProductRepository>();
mock.Setup(r => r.GetAllProducts()).Returns(new List<Product>() {p1, p2, p3});
var result = mock.Object.GetProductsByType("Type1");
Assert.AreEqual(2, result.Count());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的模拟中将 CallBase 设置为 true。这将调用原始虚拟方法或属性(如果存在)并且尚未设置为返回预设值。
Set CallBase to true on your mock. This will call the original virtual methods or properties if they exist, and haven't been set up to return a canned value.
今天我发现,在moq现在可以使用这个方法:
today I found, in moq now can use this method: