Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non Interface dependent Mocking Frameworks for C#

Tags:

c#

mocking

I am new to mocking so I might have it totally wrong here but I believe that most mocking frameworks are interface dependent. Unfortunately most of our code is not using an interface. Now the other day I saw a Mocking framework in Java that reproduced the byte code of a class\object as to not call its internal methods but you could still test that it WAS calling these methods.

My question is: does .Net have any mocking frameworks that can do a similar thing? I am looking for something free and I don't want something that requires methods to be virtual or abstract.

like image 570
Chris G Avatar asked Jul 12 '10 16:07

Chris G


People also ask

What is mocking c#?

Mocking is a process that allows you to create a mock object that can be used to simulate the behavior of a real object. You can use the mock object to verify that the real object was called with the expected parameters, and to verify that the real object was not called with unexpected parameters.

How is a mocking framework used for verification?

Verify methods were called Mocking frameworks add another way to test - checking whether methods were called, in which order, how many times and with which arguments. For example, let's say that a new test is required for adding a new user: if that user does not exist than call IDataAccess. AddNewUser method.

How do you mock a class that implements two interfaces?

You can implement multiple interfaces with a single mock instance like this: var genericRepositoryMock = new Mock<IGenericRepository<User>>(); genericRepositoryMock. Setup(m => m. CallGenericRepositoryMethod()).

Why do we need mocking framework?

Mocking frameworks complement unit testing frameworks by isolating dependencies but are not substitutes for unit testing frameworks. By isolating the dependencies, they help the unit testing process and aid developers in writing more focused and concise unit tests.


2 Answers

Microsoft Research has developed Moles for this, which is a part of Pex but can be installed independently. And it's free. There's a good introductory article (pdf) on the website that explains how to mock a static method. It takes some time before they get to the stuff you want (page 16, Task 3).

Here and here (Channel 9) you can find an example on how to stub DateTime.Now. Using Moles, you can mock anything you want.

like image 144
Ronald Wildenberg Avatar answered Oct 05 '22 08:10

Ronald Wildenberg


TypeMock Isolator can mock any .NET class, but it's not free (or cheap, even). I'm not sure how it works exactly, but it achieves the same end result.

But most of the mocking frameworks don't depend exclusively on interfaces; they should be able to handle concrete classes just as well, although they'll only be able to override virtual or abstract methods.

like image 35
Mark Rushakoff Avatar answered Oct 05 '22 07:10

Mark Rushakoff