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

This question already has answers here:
Non Interface dependent Mocking Frameworks for C#
(4 answers)
Closed 9 years ago.
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

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

There are unit testing frameworks such as TypeMock Isolator that allow you to mock non-virtual members.

To purely mock out a legacy class I would do the following:
Create an interface containing the ONLY public members that I intend on using.
eg.
public interface IDbContext {
int SaveChanges();
}
If the target legacy class is sealed then I'd create a proxy/decorator class which implements the new interface and just invoked the underlying methods/properties.
public class MyDbContextProxy : IDbContext {
DbContext _context = null;
public MyDbContextProxy(DbContext interceptedContext) {
_context = interceptedContext;
}
// decorated method
public int SaveChanges() {
_context.SaveChanges();
}
}
If the target legacy class is not sealed I'd create a descendant of the target and implement the interface. The class auto adheres to the interface.
public class MyDbContextProxy : DbContext, IDbContext {
// child adheres to interface by inheritence
}
Now you can Mock out IDbContext.

Right now there is something like Fakes Framework in VS2012. It's the successor of Moles (also able to mock classes etc. like TypeMock). It's available only in Ultimate edition, so I don't thnink it's worth Ultimate's price.
But, I'd like to discuss problem with mocking classes from other perspective.
Is it a good approach to mock classes instead of interfaces or it's some kind of a bad smell? I've never used TypeMock (it's too expensive to even consider it in small company), but people claims it's a bit "too powerful" so I'd like to use Moq/RhinoMocks, but sometimes I'd like to mock/fake one method and leave the others. It's my bad way of thinking about mocking/faking methods during tests? or it is sometimes required?

Related

Maintenance cost of unit tests which mock abstract classes

Mocking abstract classes seems appealing at first, however some change in the constructor of the abstract class can broke unit tests where the mock of the abstract class is used. So unit test isolation is not 100%. I mean no one can guarantee that the constructor of the abstract class is simple. ( I mean do not throw, do not call DB or weird things like that). I know that the constructor should be simple, but I cannot guarantee that it will stay simple all the time.
Our legacy code base is abstract class heavy, and I don't really like to mock abstract classes.
This is the main reason I prefer interfaces, or wrapper interfaces around abstract classes. Is there a way to surround the call for the base class constructor? To be honest I have never ever created abstract class during TDD, but I cannot change the legacy part of our system.
I am biased to interfaces, but i am wondering that the issue I mentioned is real, or can be bypassed.
I would use interfaces over abstract classes as unless there's a good argument against it composition is preferable than inheritance.
But are you using a code productivity tool such as ReSharper or CodeRush? They allow you to refactor code including constructors efficiently which will save you hours in instances such as this.
I think the issue you mention is absolutely real. Mocking an abstract class and using its constructor or one of its concrete methods in the test really amounts to testing the class under test and the abstract class. It's not really a unit test any more. Mocks are already fragile animals, this only gives them an additional reason to screw your tests.
I guess the solution is pretty much contained in your question - use interfaces. It's best if you can make your legacy abstract classes implement these interfaces directly, but you can also wrap them and depend on the wrapper's interface rather than on the abstract class.
Being "interface biased" might not be a bad idea when it comes to dependencies. Interfaces define a contract describing what operations are available on a collaborator. Abstract classes (not purely abstract ones, which are pretty useless compared to interfaces) describe how a family of classes behave when executing a particular operation. You don't want to depend on the how and be coupled to details, you want to be coupled to high level abstractions.
As neoistheone commented, you can generate stubs from abstract classes with the Microsoft Fakes framework.

Is there a standard method for unit testing code where dependencies do not implement interfaces?

Is there a standard method for unit testing code where dependencies do not implement interfaces? For instance, the System.Net.Http namespace only exposes concrete classes. If I'm trying to unit test a class which relies upon one of the concrete classes in System.Net.Http, should I merely construct an instance of, say, HttpRequestMessage, set it's properties and then supply this newly constructed object to the system under test? Would it make sense to subclass HttpRequestMessage and have it implement a custom interface which could then be mocked/stubbed?
The recommended practice is to wrap this object in a class of your creation, which itself implements an interface. You would then use this wrapper class in your code, and you can then supply mocked versions of this wrapper in place of the real class. You would not subclass it using this method, but rather contain it and use delegation (not to be confused with delegates!) to forward each method.
For instance, you might create a class HttpRequestMessageWrapper that inherits from IHttpRequestMessage (that you define, including all the public properties of HttpRequestMessage.. although you could probably get by with only implementing the properties you use).
Alternatively, you can use a testing framework that supports shims, which is a framework that essentially does this wrapper for you and replaces calls to the objects with shim versions. Microsoft Fakes (introduced in VS 2012 MS Test) does this.
Shims are typically used to replace common framework calls, such as DateTime.Now so you can supply a specific value during tests.
I would suggest you have a look at: AutoFixture http://autofixture.codeplex.com/ It helps you construct the object in the way you want. In your example, HttpRequestMessage, you can customize the fixture: fixture.Customize<HttpRequestMessage>(c => {});
There are many examples out there using AutoFixture in Unit Testing. Or you can post the code you want to test here and i can try to help.
Another good tool for testing legacy code is Typemock

Mock EntityEntry NHibernate

I'm doing some unit tests for an EntityEventListener from NHibernate, and I'm got stuck trying to mock FlushEvent or the EntityEntry.
As EntityEntry doesn't have a public constructor, and type Mock must be an interface, an abstract or non-sealed class.
EntityEntry ee = new EntityEntry(); //NOT
_entityEntryMock = new Mock<EntityEntry>(); //NOT
Without some elaboration, I can't say if this makes sense for you specifically, but when I hit a situation like this (a class that I can't mock with Moq and I can't build), I call in the big guns with an isolation framework. I generally use Moles, but there are other options like Typemock Isolator, and I think Moles itself is being replaced in the next .NET framework with a built-in isolator called "Fakes". But suffice it to say, you're attempting to use Moq for something it's not intended to do -- it just creates mocks "naturally" without serving as an isolation framework.

Non Interface dependent Mocking Frameworks for C#

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.
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.
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.
You can use classes instead of interfaces with both Moq and Rhino.Mocks, but the mocked methods must be virtual. Mark Rushakoff's answer on TypeMock is correct (+1).
The best option is to refactor your existing code for testability (which may take time). I'd recommend reading Working Effectively with Legacy Code by Michael Feathers.
A lot of .NET mocking frameworks use Castle Dynamic Proxy to create mocks at runtime. Hence the limitation of only allowing interface/virtual methods to be mocked comes from Castle and I think is rooted in CLR. Both MOQ and RhinoMocks are able to mock virtual methods, which is as good as it gets.
Both classes and interfaces can be
proxied, however only virtual members
can be intercepted.
My advice would be to start creating abstract bases for those classes that need to be mocked and have the concrete class extend it. Then the abstract base can be passed around and mocked. It really is a refactoring exercise that is not overly complex.

Mocking classes that aren't interfaces

I've been writing some providers in c# that inherit from the providerbase class. I've found that it's hard to write tests that use the providers as most mocking frameworks will only allow you to mock an interface.
Is there any way to mock a call to a provider that inherits from providerbase?
If not, is there a pattern that I can use to implement mocking of providers?
Mocking frameworks should be able to create for you a mock object based on a class, as long as it's got virtual members.
You may also want to take a look at Typemock
I know Rhino mocks can mock classes too, most other mocking frameworks should have no problems with this either.
Things too keep in mind: The class can't be sealed. You need to mark methods you want to mock virtual and the class needs a constructor with no arguments this can be protected, private won't work. (just tried this out)
Keep in mind that the mocking framework will just create a class that inherits from your class and creates an object of that type. So constructors will get called. This can cause unexpected behaviour in your tests.
RhinoMocks or Moq will create test doubles for classes as well as for interfaces. The type has to have virtual methods or be abstract though. The Typemock isolator gets around this.
I'd suggest that the objects you want to mock probably should be abstract (dependency inversion principle).

Categories