[Unit-testing] How do you mock a Sealed class?


For .NET, you could use something like TypeMock, which uses the profiling API and allows you to hook into calls to nearly anything.


Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird.

So, What is the best way you mock sealed classes?

Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer.

But here are some of the .NET opinions:

How do you mock a Sealed class?

My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9).

Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default.

I believe that Moles, from Microsoft Research, allows you to do that. From the Moles page:

Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.

UPDATE: there is a new framework called "Fakes" in the upcoming VS 11 release that is designed to replace Moles:

The Fakes Framework in Visual Studio 11 is the next generation of Moles & Stubs, and will eventually replace it. Fakes is different from Moles, however, so moving from Moles to Fakes will require some modifications to your code. A guide for this migration will be available at a later date.

Requirements: Visual Studio 11 Ultimate, .NET 4.5

Think of containment as a has a relationship. A car "has an" engine, a person "has a" name, etc.

Think of inheritance as an is a relationship. A car "is a" vehicle, a person "is a" mammal, etc.

I take no credit for this approach. I took it straight from the Second Edition of Code Complete by Steve McConnell, Section 6.3.

How can I mock an OracleConnection and OracleCommand?

You can make changes to use IDbConnection and IDbCommand (use interfaces and have a factory to provide the real objects in main code and mock objects in test - normally using Dependency Injection)

Moq can only mock Interfaces and virtual methods.