<p><a href="http://www.google.com/search?q=how%20to%20mock%20sealed%20class" rel="noreferrer">Mocking sealed classes</a> can be quite a pain.  I currently favor an <a href="http://en.wikipedia.org/wiki/Adapter_pattern" rel="noreferrer">Adapter pattern</a> to handle this, but something about just keeps feels weird.  </p>

<p><strong>So, What is the best way you mock sealed classes?</strong></p>

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

<p>But here are some of the .NET opinions:</p>

<ul>
<li><a href="http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx" rel="noreferrer">Why Duck Typing Matters for C#
Develoepers</a> </li>
<li><a href="http://cs.rthand.com/blogs/blog_with_righthand/archive/2008/07/22/Creating-wrappers-for-sealed-and-other-types-for-mocking.aspx" rel="noreferrer">Creating wrappers
for sealed and other types for
mocking</a></li>
<li><a href="http://weblogs.asp.net/cibrax/archive/2008/05/16/unit-tests-for-wcf.aspx" rel="noreferrer">Unit tests for WCF (and Moq)</a></li>
</ul>

[{'answer_id': 6543, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 0, 'selected': False, 'text': "<p>Is there a way to implement a sealed class from an interface... and mock the interface instead?</p>\n\n<p>Something in me feels that having sealed classes is wrong in the first place, but that's just me :)</p>\n"}, {'answer_id': 6716, 'author': 'abyx', 'author_id': 573, 'author_profile': 'https://Stackoverflow.com/users/573', 'pm_score': 5, 'selected': True, 'text': '<p>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 <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html" rel="noreferrer">latest post</a> (See point 9).</p>\n\n<p>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.</p>\n'}, {'answer_id': 31731, 'author': 'Haacked', 'author_id': 598, 'author_profile': 'https://Stackoverflow.com/users/598', 'pm_score': 4, 'selected': False, 'text': '<p>For .NET, you could use something like <a href="https://www.typemock.com/" rel="nofollow noreferrer">TypeMock</a>, which uses the profiling API and allows you to hook into calls to nearly anything.</p>\n'}, {'answer_id': 31754, 'author': 'Brad Wilson', 'author_id': 1554, 'author_profile': 'https://Stackoverflow.com/users/1554', 'pm_score': 3, 'selected': False, 'text': "<p>The problem with TypeMock is that it excuses bad design. Now, I know that it is often <em>someone else's</em> bad design that it's hiding, but permitting it into your development process can lead very easily to permitting your own bad designs.</p>\n\n<p>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.</p>\n"}, {'answer_id': 1864760, 'author': 'Steve Guidi', 'author_id': 131407, 'author_profile': 'https://Stackoverflow.com/users/131407', 'pm_score': 1, 'selected': False, 'text': '<p>I generally take the route of creating an interface and adaptor/proxy class to facilitate mocking of the sealed type.  However, I\'ve also experimented with skipping creation of the interface and making the proxy type non-sealed with virtual methods.  This worked well when the proxy is really a natural base class that encapsulates and users part of the sealed class.</p>\n<p>When dealing with code that required this adaptation, I got tired of performing the same actions to create the interface and proxy type so I implemented a library to automate the task.</p>\n<p>The code is somewhat more sophisticated than the sample given in the article you reference, as it produces an assembly (instead of source code), allows for code generation to be performed on any type, and doesn\'t require as much configuration.</p>\n<p>For more information, please refer to <a href="http://jolt.codeplex.com/wikipage?title=Jolt.Testing.CodeGeneration.Proxy&amp;referringTitle=Jolt.Testing" rel="nofollow noreferrer">this page</a>.</p>\n'}, {'answer_id': 1885720, 'author': 'kyoryu', 'author_id': 129175, 'author_profile': 'https://Stackoverflow.com/users/129175', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<p>It also makes it easier to switch my dependencies in the long run.</p>\n"}, {'answer_id': 2587888, 'author': 'Adam Lenda', 'author_id': 104846, 'author_profile': 'https://Stackoverflow.com/users/104846', 'pm_score': 1, 'selected': False, 'text': '<p>It is perfectly reasonable to mock a sealed class because many framework classes are sealed.</p>\n\n<p>In my case I\'m trying to mock .Net\'s MessageQueue class so that I can TDD my graceful exception handling logic.</p>\n\n<p>If anyone has ideas on how to overcome Moq\'s error regarding "Invalid setup on a non-overridable member", please let me know.</p>\n\n<p>code:</p>\n\n<pre><code>    [TestMethod]\n    public void Test()\n    {\n        Queue&lt;Message&gt; messages = new Queue&lt;Message&gt;();\n        Action&lt;Message&gt; sendDelegate = msg =&gt; messages.Enqueue(msg);\n        Func&lt;TimeSpan, MessageQueueTransaction, Message&gt; receiveDelegate =\n            (v1, v2) =&gt;\n            {\n                throw new Exception("Test Exception to simulate a failed queue read.");\n            };\n\n        MessageQueue mockQueue = QueueMonitorHelper.MockQueue(sendDelegate, receiveDelegate).Object;\n    }\n    public static Mock&lt;MessageQueue&gt; MockQueue\n                (Action&lt;Message&gt; sendDelegate, Func&lt;TimeSpan, MessageQueueTransaction, Message&gt; receiveDelegate)\n    {\n        Mock&lt;MessageQueue&gt; mockQueue = new Mock&lt;MessageQueue&gt;(MockBehavior.Strict);\n\n        Expression&lt;Action&lt;MessageQueue&gt;&gt; sendMock = (msmq) =&gt; msmq.Send(It.IsAny&lt;Message&gt;()); //message =&gt; messages.Enqueue(message);\n        mockQueue.Setup(sendMock).Callback&lt;Message&gt;(sendDelegate);\n\n        Expression&lt;Func&lt;MessageQueue, Message&gt;&gt; receiveMock = (msmq) =&gt; msmq.Receive(It.IsAny&lt;TimeSpan&gt;(), It.IsAny&lt;MessageQueueTransaction&gt;());\n        mockQueue.Setup(receiveMock).Returns&lt;TimeSpan, MessageQueueTransaction&gt;(receiveDelegate);\n\n        return mockQueue;\n    }\n</code></pre>\n'}, {'answer_id': 2587936, 'author': 'Mathias', 'author_id': 114519, 'author_profile': 'https://Stackoverflow.com/users/114519', 'pm_score': 4, 'selected': False, 'text': '<p>I believe that <a href="http://research.microsoft.com/en-us/projects/Pex/" rel="noreferrer">Moles</a>, from Microsoft Research, allows you to do that. From the Moles page:</p>\n<blockquote>\n<p>Moles may be used to detour any .NET\nmethod, including non-virtual/static\nmethods in sealed types.</p>\n</blockquote>\n<p><strong>UPDATE:</strong> there is a new framework called &quot;Fakes&quot; in the upcoming VS 11 release that is designed to replace Moles:</p>\n<blockquote>\n<p>The <a href="http://aka.ms/vs11-fakes" rel="noreferrer">Fakes Framework in Visual Studio 11</a> is the next generation of Moles &amp; 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.</p>\n<p><strong>Requirements</strong>: Visual Studio 11 Ultimate, .NET 4.5</p>\n</blockquote>\n'}, {'answer_id': 10003776, 'author': 'dodgy_coder', 'author_id': 507950, 'author_profile': 'https://Stackoverflow.com/users/507950', 'pm_score': 1, 'selected': False, 'text': '<p>Although it\'s currently only available in beta release, I think it\'s worthwhile keeping in mind the <a href="http://msdn.microsoft.com/en-us/library/hh549176%28v=vs.110%29.aspx" rel="nofollow noreferrer">shim</a> feature of the new <a href="http://aka.ms/vs11-fakes" rel="nofollow noreferrer">Fakes framework</a> (part of the <a href="http://www.microsoft.com/visualstudio/11/en-us" rel="nofollow noreferrer">Visual Studio 11</a> Beta release).</p>\n<blockquote>\n<p>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.</p>\n</blockquote>\n<p>Personally, I was looking at using this to mock the methods on sealed framework classes such as DrawingContext.</p>\n'}, {'answer_id': 30200039, 'author': 'hassan', 'author_id': 4893007, 'author_profile': 'https://Stackoverflow.com/users/4893007', 'pm_score': 3, 'selected': False, 'text': '<p>I came across this problem recently and after reading / searching web, seems like there is no easy way around except to use another tool as mentioned above.\nOr crude of handling things as I did:</p>\n<ul>\n<li><p>Create instance of sealed class without getting constructor called.</p>\n</li>\n<li><p><code>System.Runtime.Serialization.FormatterServices.GetUninitializedObject(instanceType)</code>;</p>\n</li>\n<li><p>Assign values to your properties / fields via reflection</p>\n</li>\n<li><p><code>YourObject.GetType().GetProperty(&quot;PropertyName&quot;).SetValue(dto, newValue, null);</code></p>\n</li>\n<li><p><code>YourObject.GetType().GetField(&quot;FieldName&quot;).SetValue(dto, newValue);</code></p>\n</li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/6484', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307/']