How do you mock a Sealed class?

Viewed 48833

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:

10 Answers

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

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.

The problem with TypeMock is that it excuses bad design. Now, I know that it is often someone else's bad design that it's hiding, but permitting it into your development process can lead very easily to permitting your own bad designs.

I think if you're going to use a mocking framework, you should use a traditional one (like Moq) and create an isolation layer around the unmockable thing, and mock the isolation layer instead.

I almost always avoid having dependencies on external classes deep within my code. Instead, I'd much rather use an adapter/bridge to talk to them. That way, I'm dealing with my semantics, and the pain of translating is isolated in one class.

It also makes it easier to switch my dependencies in the long run.

Although it's currently only available in beta release, I think it's worthwhile keeping in mind the shim feature of the new Fakes framework (part of the Visual Studio 11 Beta release).

Shim types provide a mechanism to detour any .NET method to a user defined delegate. Shim types are code-generated by the Fakes generator, and they use delegates, which we call shim types, to specify the new method implementations. Under the hood, shim types use callbacks that were injected at runtime in the method MSIL bodies.

Personally, I was looking at using this to mock the methods on sealed framework classes such as DrawingContext.

Is there a way to implement a sealed class from an interface... and mock the interface instead?

Something in me feels that having sealed classes is wrong in the first place, but that's just me :)

Related