Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking using 'traditional' Record/Replay vs Moq model

I'm new to mocks and am deciding on a mock framework. The Moq home quotes

Currently, it's the only mocking library that goes against the generalized and somewhat unintuitive (especially for novices) Record/Reply approach from all other frameworks.

Can anyone explain simply what the Record/Replay approach is and how Moq differs? What are the pros and cons of each especially from the point of deciding a framework?

Thanks.

like image 823
Fung Avatar asked Mar 16 '09 13:03

Fung


People also ask

What can be mocked with Moq?

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.

What is Moq mocking framework?

Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.

What is NUnit and Moq?

NUnit is a unit testing framework for . NET languages, and Moq is the most popular mocking framework for . NET. I assume the reader is familiar with C# projects, Visual Studio IDE, and the Nuget package manager for managing dependencies. I will cover creating Unit tests using NUnit and Moq.

Is Moq a testing framework?

The Moq framework is an open source unit testing framework that works very well with .


1 Answers

The Record/Replay approach is supported by RhinoMocks. The basic idea is that your test execution is divided into two phases, the record phase and the replay phase. To be a little bit more concrete

var repo = new MockRepository();
var dependency = repo.DynamicMock<IDependency>();
With.Mocks(repo).Expecting(delegate {
         Expect.Call(dependency.AMethod(1)).Return(result);                    
      }).Verify(delegate {
         var sut = new Sut(wrappee);
         sut.DoStuffThatCallsAMethod();
         Assert.IsTrue(sut.ResultState);
      });

So the Expecting block is the Record phase and the Verify block is the Replay phase.

The Moq variant of this code would be

var dependency = new Mock<IDependency>();
dependency.Expect(dep => dep.AMethod(1)).Returns(result);          
var sut = new Sut(wrappee.Object);
sut.DoStuffThatCallsAMethod();
Assert.IsTrue(sut.ResultState);

Which as you can see is much nicer to read. I used to use RhinoMocks but since I discovered Moq I only use Moq. I find it to be produce much more readable code. So my advice would be to go for Moq.

like image 188
Bas Bossink Avatar answered Nov 16 '22 04:11

Bas Bossink