How do you mock the Sealed class?

Buying up closed classes can be pretty painful. I am currently approving an adapter template to handle this, but something seems to just keep weird.

So, what is the best way you mock private classes?

Java answers are more than welcome. In fact, I was expecting the Java community to handle this already and have a lot to offer.

But here are some of the views of .NET:

+54
language-agnostic unit-testing tdd mocking
Aug 09 2018-08-08T00:
source share
10 answers

My general rule is that the objects I need for the layout must have a common interface. I think this is the right design and makes testing a lot easier (and usually this is what you get if you are doing TDD). You can read more about this on the Google Testing blog last post (see Clause 9).

In addition, I worked mainly in Java over the past 4 years, and I can say that I can count, on the one hand, the number of times I created the final (sealed) class. Another rule: I always have a good reason to seal the class, and not seal it by default.

+7
Aug 09 '08 at 9:40
source share

For .NET, you can use something like TypeMock , which uses the profiling API and allows you to connect to calls on almost everything.

+17
Aug 28 '08 at 6:44
source share

I believe that Moles from Microsoft Research can do this. On the Moles page:

Moths can be used to bypass any .NET. method, including non-virtual / static methods in private types.

UPDATE: A new framework called "Fakes" has appeared in the upcoming release of VS 11, which is intended to replace Moles:

The Fakes Framework in Visual Studio 11 is the next generation of Moles and Stubs and will eventually replace it. Fakes are different from Moles, however, so moving from Moles to Fakes will require some changes to your code. Guidance on this migration will be available later.

Requirements : Visual Studio 11 Ultimate, .NET 4.5

+12
Apr 6 '10 at 20:12
source share

The problem with TypeMock is that it justifies poor design. Now I know that often the bad design of another person, which he hides, but allowing it in the development process, can very easily resolve your own bad projects.

I think if you are going to use a fake framework, you should use a traditional one (like Moq) and create an insulating layer around an unmarkable thing and instead make fun of the insulating layer.

+4
Aug 28 '08 at 7:04
source share

I almost always avoid dependency on external classes inside my code. Instead, I would rather use an adapter / bridge to talk to them. Thus, I deal with my semantics, and the pain of translation is isolated in one class.

It also facilitates the transition of my dependencies in the long run.

+4
Dec 11 '09 at 4:08
source share

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

Something in me feels that the classes are first of all mistakenly sealed, but it's just me :)

+1
Aug 09 '08 at 2:21
source share

I usually take the path of creating the interface and adapter / proxy class to ease the mockery of the closed type. However, I also experimented with skipping interface creation and creating a proxy type that was not sealed by virtual methods. This worked well when the proxy server is indeed a natural base class that encapsulates and uses part of the private class.

When working with code that required this adaptation, I was tired of performing the same steps to create an interface and proxy type, so I implemented a library to automate the task.

The code is somewhat more complex than the sample specified in the article you are referencing, since it creates an assembly (instead of the source code), allows you to generate code for any type and does not require such a configuration.

See this page for more information.

+1
Dec 08 '09 at 5:14
source share

It makes perfect sense to mock a private class because many wireframe classes are sealed.

In my case, I'm trying to make fun of the .Net MessageQueue class so that I can TDD use my graceful exception handling logic.

If anyone has ideas on how to overcome Moq's error regarding โ€œInvalid setting for an uncaught member,โ€ let me know.

the code:

[TestMethod] public void Test() { Queue<Message> messages = new Queue<Message>(); Action<Message> sendDelegate = msg => messages.Enqueue(msg); Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate = (v1, v2) => { throw new Exception("Test Exception to simulate a failed queue read."); }; MessageQueue mockQueue = QueueMonitorHelper.MockQueue(sendDelegate, receiveDelegate).Object; } public static Mock<MessageQueue> MockQueue (Action<Message> sendDelegate, Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate) { Mock<MessageQueue> mockQueue = new Mock<MessageQueue>(MockBehavior.Strict); Expression<Action<MessageQueue>> sendMock = (msmq) => msmq.Send(It.IsAny<Message>()); //message => messages.Enqueue(message); mockQueue.Setup(sendMock).Callback<Message>(sendDelegate); Expression<Func<MessageQueue, Message>> receiveMock = (msmq) => msmq.Receive(It.IsAny<TimeSpan>(), It.IsAny<MessageQueueTransaction>()); mockQueue.Setup(receiveMock).Returns<TimeSpan, MessageQueueTransaction>(receiveDelegate); return mockQueue; } 
+1
Apr 6 '10 at 20:05
source share

I ran into this problem recently and after reading / searching the Internet, it seems that there is no easy way other than using the other tool mentioned above. Or rough handling things like me:

  • Create an instance of a private class without calling the constructor.
  • System.Runtime.Serialization.FormatterServices.GetUninitializedObject (instanceType);

  • Assign values โ€‹โ€‹to your properties / fields using reflection

  • YourObject.GetType (). GetProperty ("PropertyName"). SetValue (dto, newValue, null);
  • YourObject.GetType (). GetField ("FieldName"). SetValue (dto, newValue);
+1
May 12 '15 at 19:42
source share

Despite the fact that it is currently only available in beta, I think it should be borne in mind the shim function of the new Faces framework (part of Visual Studio 11 beta).

PWM types provide a mechanism to bypass any .NET method to a specific delegate. Firmware types are generated by the Fakes generator code, and they use delegates, which we call shim types, to indicate new method implementations. Under the hood, pad types use callbacks that were entered at runtime in MSIL methods.

Personally, I was looking for using this to mock methods on private framework classes such as DrawingContext.

0
Apr 04 '12 at 1:24
source share



All Articles