How do you mock a Sealed class?

前端 未结 10 2185
鱼传尺愫
鱼传尺愫 2020-11-27 15:27

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 t

相关标签:
10条回答
  • 2020-11-27 15:47

    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 :)

    0 讨论(0)
  • 2020-11-27 15:48

    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.

    0 讨论(0)
  • 2020-11-27 15:50

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

    0 讨论(0)
  • 2020-11-27 15:59

    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.

    0 讨论(0)
提交回复
热议问题