用Moq调用原始方法

rod*_*dbv 46 c# moq mocking

我有一个带有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();
}
Run Code Online (Sandbox Code Playgroud)

因此,在我的测试中,我想模拟对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());
Run Code Online (Sandbox Code Playgroud)

wom*_*omp 74

在模拟上将CallBase设置为true.这将调用原始虚拟方法或属性(如果存在),并且尚未设置为返回固定值.

var mock = new Mock<ProductRepository>() { CallBase = true };
Run Code Online (Sandbox Code Playgroud)


小智 12

今天我发现,在moq现在可以使用这个方法:

 mockObj.Setup(obj => obj.FunctionA()).CallBase();
Run Code Online (Sandbox Code Playgroud)