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
The commercial edition allows you to mock concrete objects without having to change anything in their interface. This is an elevated feature.
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.
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.
You can implement multiple interfaces with a single mock instance like this: var genericRepositoryMock = new Mock<IGenericRepository<User>>(); genericRepositoryMock. Setup(m => m. CallGenericRepositoryMethod()).
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>
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With