Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling original method with Moq

Tags:

c#

mocking

moq

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());
like image 903
rodbv Avatar asked Jun 18 '10 21:06

rodbv


People also ask

How do you call an original method in mock?

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.

What can be mocked with Moq?

Unit testing is a powerful way to ensure that your code works as intended. It's a great way to combat the common “works on my machine” problem. Using Moq, you can mock out dependencies and make sure that you are testing the code in isolation. Moq is a mock object framework for .

Can you mock a class with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can't be static or sealed, and the method being mocked should be marked as virtual.

How does Moq mock work?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.


2 Answers

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.

var mock = new Mock<ProductRepository>() { CallBase = true };
like image 176
womp Avatar answered Oct 13 '22 07:10

womp


today I found, in moq now can use this method:

 mockObj.Setup(obj => obj.FunctionA()).CallBase();
like image 37
JFHB Avatar answered Oct 13 '22 07:10

JFHB