views:

826

answers:

4

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?

+4  A: 

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

cruizer
hmm... I've been using NMock and it would appear that it's a limitation of NMock not a limitation of Mocking in general.. thanks for the link
lomaxx
A: 

I'm not really getting it. As long as your mock class inherits from the "original" (non-mock) one, the mock class should be able to be a substitute for the original class. No interface necessary. At least in Java, that is.

xmjx
well that's because you're talking about Java; the question is about C#. In Java methods are virtual by default, so they can be overridden by a mock; in C# that's not the case -- it has to be explicitly marked virtual! Sucks, I know... :(
cruizer
+4  A: 

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.

Mendelt
A: 

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

Hamish Smith