0

Using Moq framework, it is not allowed to mock a class in C# which is sealed. Same goes for many other frameworks as well. But why is it not allowed?

0

1 Answer 1

7

Mocking a class usually works by using reflection to construct a subclass which has methods and properties that do nothing (or whatever is required for the mock).

"Sealed" classes cannot be subclassed, so they cannot be mocked. If you have a sealed class X, then only instances of X will satisfy the typechecker for function parameters which require X.

Three solutions:

  • make an interface, which the sealed class implements, and make functions take the interface. They can then accept mock objects as well. You do then lose some of the optimizer benefits of sealed.

  • unseal the class

  • use real objects rather than mocks, which is easier if they don't have too much behavior.

4
  • Good answer. Still I think "don't have too much behavior." is not the right criterion. A better criterion is "Can be constructed and initialized easily" (in memory, without using an external service or the need of creating tons of helper objects first).
    – Doc Brown
    Nov 8, 2023 at 12:31
  • 1
    IOW, it has nothing to do with it "not being allowed". It is simply not possible. Nov 8, 2023 at 12:52
  • I also found a useful link which explains an alternate approach while dealing with mocking of sealed or static classes. blackwasp.co.uk/MockSealedStatic.aspx
    – Akshunya
    Nov 8, 2023 at 13:39
  • @JörgWMittag or "not allowed" by a language rule, rather than "not allowed" by a library-writer decision
    – Caleth
    Nov 9, 2023 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.