简体   繁体   English

使用 Moq 调用原始方法

[英]Calling original method with Moq

I have a ProductRepository with 2 methods, GetAllProducts and GetProductByType, and I want to test the logic at GetProductByType.我有一个 ProductRepository 有 2 个方法,GetAllProducts 和 GetProductByType,我想测试 GetProductByType 的逻辑。 Internally, GetProductByType makes a call to GetAllProducts and then filters the correct ones.在内部,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();
}

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.因此,在我的测试中,我想模拟对 GetAllProducts 的调用,因此它返回在我的测试中定义的产品列表,然后调用原始的 GetProductsByType,它将消耗模拟的 GetAllProducts。

I'm trying something like the code below but the original GetProductByType is not executed, it is mocked-out as well.我正在尝试类似下面的代码,但原始的 GetProductByType 没有执行,它也被模拟出来了。 In TypeMock I have a CallOriginal method that fixes this, but I can't figure it out with Moq.在 TypeMock 中,我有一个 CallOriginal 方法可以解决这个问题,但我无法用 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());

Set CallBase to true on your mock.在您的模拟上将 CallBase 设置为 true。 This will call the original virtual methods or properties if they exist, and haven't been set up to return a canned value.这将调用原始虚拟方法或属性(如果它们存在),并且尚未设置为返回固定值。

var mock = new Mock<ProductRepository>() { CallBase = true };

今天我发现,在起订量现在可以使用这种方法:

 mockObj.Setup(obj => obj.FunctionA()).CallBase();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM