Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking classes which dont have interface and even no virtual methods [duplicate]

Tags:

c#

I want to mock a particular method of a class, problem i am facing while mocking is that class does not have any interface and also that method is not virtual.

Can any one suggest any other way to implement mocking.

Any help will be appreciated. Thanks in advance

like image 225
Jash Avatar asked Mar 26 '12 06:03

Jash


People also ask

Can you mock without an interface?

The commercial edition allows you to mock concrete objects without having to change anything in their interface. This is an elevated feature.

Can I mock non virtual methods C#?

Moq cannot mock non virtual methods on classes. Either use other mocking frameworks such as Type mock Isolator which actually weaves IL into your assembly or place an interface on EmailService and mock that.

What is interface mocking?

Mock Interfaces. JustMock allows you to easily create a mock object without maintaining its physical implementation, which reduces the creation and maintenance costs significantly. This feature is a part of the fastest, most flexible and complete mocking tool for crafting unit tests.

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()).


2 Answers

Option 1: TypeMock Isolator or something similar, which allows deeper messing with the code than normal mocking.

Option 2: (Preferred if possible) Alter the design, e.g. by introducing an interface and creating a delegating implementation which just calls into the existing test-unfriendly class. You can then depend on the interface, mock it in tests, and delegate to the "real" implementation for production.

This is assume you really should be mocking the class, of course. You shouldn't automatically mock everything your code uses - I tend to think of mocking "services" of some description, whereas I wouldn't mock (for example) List<T>.

like image 51
Jon Skeet Avatar answered Sep 30 '22 21:09

Jon Skeet


I suggest refactoring your code ;) All mocking frameworks which creates mock by deriving from mocked class requires methods to be virtual (this is more CLR requirement rather than mocking framework).

To mock non-virtual methods you can use profiler-based frameworks like Moles or TypeMock Isolator, however this requires to run test runner using special runner which will attach CLR profiler to process

like image 45
Novakov Avatar answered Sep 30 '22 20:09

Novakov