Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of Moq?

Tags:

I keep seeing this referred to on DotNetKicks etc... Yet cannot find out exactly what it is (In English) or what it does? Could you explain what it is, or why I would use it?

like image 898
YodasMyDad Avatar asked Mar 24 '09 19:03

YodasMyDad


2 Answers

Moq is a mocking framework for C#/.NET. It is used in unit testing to isolate your class under test from its dependencies and ensure that the proper methods on the dependent objects are being called. For more information on mocking you may want to look at the Wikipedia article on Mock Objects.

Other mocking frameworks (for .NET) include JustMock, TypeMock, RhinoMocks, nMock, .etc.

like image 150
tvanfosson Avatar answered Oct 19 '22 12:10

tvanfosson


In simple English, Moq is a library which when you include in your project give you power to do Unit Testing in easy manner. Why? Because one function may call another, then another and so on. But in real what is needed, just the return value from first call to proceed to next line. Moq helps to ignore actual call of that method and instead you return what that function was returning. and verify after all lines of code has executed, what you desired is what you get or not. Too Much English, so here is an example:

String Somethod() {   IHelper help = new IHelper();   String first = help.firstcall();   String second= secondcall(first);   return second; } 

Now, here first is needed to for secondcall(), but you can not actually call help.firstcall() as it in some other layer. So Mocking is done, faking that method was called:

[TestMethod] public void SomeMethod_TestSecond {   mockedIHelper.Setup(x=>x.firstcall()).Returns("Whatever i want");   } 

Here, think, SetUP as faking method call, we are just interested in Returns.

like image 31
Rajesh Mishra Avatar answered Oct 19 '22 14:10

Rajesh Mishra