Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mock a Sealed class?

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:

like image 851
Brett Veenstra Avatar asked Aug 09 '08 00:08

Brett Veenstra


People also ask

Can you mock sealed classes?

It is perfectly reasonable to mock a sealed class because many framework classes are sealed.

Can you override a sealed class?

You can't inherit from a sealed class, so no inheritance, no override. The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. When applied to a class, the sealed modifier prevents other classes from inheriting from it.

Can you instantiate a sealed class?

Sealed classes cannot be instantiated directly. Sealed classes cannot have public constructors (The constructors are private by default). Sealed classes can have subclasses, but they must either be in the same file or nested inside of the sealed class declaration.

How do you call a sealed class?

Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.


2 Answers

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

like image 116
Haacked Avatar answered Sep 21 '22 17:09

Haacked


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.

like image 37
abyx Avatar answered Sep 21 '22 17:09

abyx