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).
Related
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? 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
Most of the examples given in mocking framework website is to mock Interface. Let say NSubstitute that I'm currently using, all their mocking examples is to mock interface.
But in reality, I saw some developer mock concrete class instead. Is it recommended to mock concrete class?
In theory there is absolutely no problem mocking a concrete class; we are testing against a logical interface (rather than a keyword interface), and it does not matter whether that logical interface is provided by a class or interface.
In practice .NET/C# makes this a bit problematic. As you mentioned a .NET mocking framework I'm going to assume you're restricted to that.
In .NET/C# members are non-virtual by default, so any proxy-based methods of mocking behaviour (i.e. derive from the class, and override all the members to do test-specific stuff) will not work unless you explicitly mark the members as virtual. This leads to a problem: you are using an instance of a mocked class that is meant to be completely safe in your unit test (i.e. won't run any real code), but unless you have made sure everything is virtual you may end up with a mix of real and mocked code running (this can be especially problematic if there is constructor logic, which always runs, and is compounded if there are other concrete dependencies to be new'd up).
There are a few ways to work around this.
Use interfaces. This works and is what we advise in the NSubstitute documentation, but has the downside of potentially bloating your codebase with interfaces that may not actually be needed. Arguably if we find good abstractions in our code we'll naturally end up with neat, reusable interfaces we can test to. I haven't quite seen it pan out like that, but YMMV. :)
Diligently go around making everything virtual. An arguable downside to this is that we're suggesting all these members are intended to be extension points in our design, when we really just want to change the behaviour of the whole class for testing. It also doesn't stop constructor logic running, nor does it help if the concrete class requires other dependencies.
Use assembly re-writing via something like the Virtuosity add-in for Fody, which you can use to modify all class members in your assembly to be virtual.
Use a non-proxy based mocking library like TypeMock (paid), JustMock (paid), Microsoft Fakes (requires VS Ultimate/Enterprise, though its predecessor, Microsoft Moles, is free) or Prig (free + open source). I believe these are able to mock all aspects of classes, as well as static members.
A common complaint lodged against the last idea is that you are testing via a "fake" seam; we are going outside the mechanisms normally used for extending code to change the behaviour of our code. Needing to go outside these mechanisms could indicate rigidity in our design. I understand this argument, but I've seen cases where the noise of creating another interface/s outweighs the benefits. I guess it's a matter of being aware of the potential design issue; if you don't need that feedback from the tests to highlight design rigidity then they're great solutions.
A final idea I'll throw out there is to play around with changing the size of the units in our tests. Typically we have a single class as a unit. If we have a number of cohesive classes as our unit, and have interfaces acting as a well-defined boundary around that component, then we can avoid having to mock as many classes and instead just mock over a more stable boundary. This can make our tests a more complicated, with the advantage that we're testing a cohesive unit of functionality and being encouraged to develop solid interfaces around that unit.
Hope this helps.
Update:
3 years later I want to admit that I changed my mind.
In theory I still do not like to create interfaces just to facilitate creation of mock objects. In practice ( I am using NSubstitute) it is much easier to use Substitute.For<MyInterface>() rather than mock a real class with multiple parameters, e.g. Substitute.For<MyCLass>(mockedParam1, mockedParam2, mockedParam3), where each parameter should be mocked separately. Other potential troubles are described in NSubstitute documentation
In our company the recommended practice now is to use interfaces.
Original answer:
If you don't have a requirement to create multiple implementations of the same abstraction, do not create an interface.
As it pointed by David Tchepak, you don't want to bloating your codebase with interfaces that may not actually be needed.
From http://blog.ploeh.dk/2010/12/02/InterfacesAreNotAbstractions.aspx
Do you extract interfaces from your classes to enable loose
coupling? If so, you probably have a 1:1 relationship between your
interfaces and the concrete classes that implement them.
That’s probably not a good sign, and violates the Reused Abstractions
Principle (RAP).
Having only one implementation of a given interface is a code smell.
If your target is the testability, i prefer the second option from David Tchepak's answer above.
However I am not convinced that you have to make everything virtual. It's sufficient to make virtual only the methods, that you are going to substitute.
I also will add a comment next to the method declaration that method is virtual only to make it substitutable for unit test mocking.
However note that substitution of concrete classes instead of interfaces has some limitations.
E.g. for NSubstitute
Note: Recursive substitutes will not be created for classes, as
creating and using classes can have potentially unwanted side-effects
.
The question is rather: Why not?
I can think of a couple of scenarios where this is useful, like:
Implementation of a concrete class is not yet complete, or the guy who did it is unreliable. So I mock the class as it is specified and test my code against it.
It can also be useful to mock classes that do things like database access. If you don't have a test database you might want to return values for your tests that are always constant (which is easy by mocking the class).
Its not that it is recommended, it's that you can do this if you have no other choice.
Usually well designed project rely on defining interfaces for your separate components so you can tests each of them in isolation by mocking the other ones. But if you are working with legacy code /code that you are not allowed to change and still want to test your classes then you have no choice and you cannot be criticized for it (assuming you made the effort to try to switch these components to interfaces and were denied the right to).
Supposed we have:
class Foo {
fun bar() = if (someCondition) {
“Yes”
} else {
“No”
}
}
There’s nothing preventing us to do the following mocking in the test code:
val foo = mock<Foo>()
whenever(foo.bar()).thenReturn(“Maybe”)
The problem is it is setting up incorrect behavior of class Foo. The real instance of class Foo will never be able to return “Maybe”.
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?
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.