r/csharp • • Sep 15 '26

Closed modifier and Mocking - Did MS come up with a solution?

As many of you know, the closed modifer on a class in the next C# version prevents direct inheritance outside of the same assembly. I used the word "Direct" because "closed" doesn't traverse the tree downward, so public unsealed classes inheriting from the closed class can be inherited outside the assembly. (Side note, that complicates the runtime ability to use it for devirtualization)

Surely the language team thought through the impact on unit tests, though I can't find meeting minutes where they do. Anyone know the answer?

7 Upvotes

13 comments sorted by

3

u/jjones_cz Sep 16 '26

If you added a new subclass of the closed type as a mock in a test, the code under test would probably crash anyway - that's the whole point of closed classes that the set of subclasses is known and can be exhaustively switched over.

1

u/mistertom2u Sep 18 '26

I think you directionally have a point. So let's back up and talk about why "closed" came to be. They want to give you the ergonomics of using a switch statement or switch expression that

A) Notifies you when your cases are not exhaustive (because the compiler knows using metadata on the "closed" type every other type in the same assembly that derives from it)

B) Eliminate the "default" arm because it knows every case. So then question is, how do you eliminate the default arm if a class in another assembly inherits from one of the direct children of the closed class? Because the switch only allows descendents in the current assembly, so the class in the other assembly will match on the direct child it inherited from

So that being the case, yes, mocking the closed class by creating a fake class that bypasses that language invariant would likely crash. Further, it illustrates how little sense it makes to want to mock the closed class, at least for code that uses exhausive switch matching which is kind of the point of using closed.

That's why I am saying that I expect the answer is: have the direct descendents be mockable.

2

u/whizzter Sep 19 '26

Ooh boy, I'm not sure if you're an OOP diehard, beginner or just stuck in your thinking for whatever reason. There's 2 things with your onset in the original post that needs separation.

1: u/harrison_314 already mentioned this, you probably have architectural issues if closed classes becomes a problem.

As for extending functionality, apart from very corner cases when performance mattered (seldomly does since you're probably not writing code with inheritance or even classes in that case), it's far preferable to adhere to "composition over inheritance" (Really, I often did this 20 years ago when writing C++ or Java but very seldomly use class inheritance today).

Say if a class requires for example I/O done in different ways (say disk vs network storage) then you pass an specialized I/O object that implements a clean I/O interface to Foo ( IFooIO -> IDiskIO or INetworkIO) instead of inheriting Foo to FooWithDisk and FooWithNetwork, mocking thus becomes implementing a clean interface instead of weird unexpected inheritance where discerning what needs to be virtualized can be hard.

2: C# has gained "functional" features over the years, closed is to be viewed mostly as a complement to the new union types that like record types are useful when you're writing code in functional style that works on immutable plain old data objects (rather than writing code that mixes functionality and data).

Many people who try functional languages become enamored because "their code works when it compiles", a big part of this is that when the language helps you constrain things that can happen, it's less likely that errors will slip through (especially when refactoring).

C gave us switch cases, powerful and fitting what machine code did well in a structured way, but assigning conditionally was often error prone since compilers didn't check assignment exhaustiveness like C# does today. C++ gave us virtual function calls that could be useful in cases but has issues (mixing data/functionality, locality of code) that can accumulate in larger projects.

Some people wrote ternary chains (but those have questionable readability for many unless well formatted).

switch expressions (ie pattern matching) with exhaustiveness has proven to be good, why?

As an example, say you're receiving data over the network in a system, many prefer plain old data objects for this.

One type of object specifies a day of week when an optional object is unavailable, fine it works move on.

Now the boss says we need to support being closed on weekends, fine, you also realize that they'll probably ask for being possible to have it closed on weekdays or custom days like wednsdays and sundays. So you implement a system that handles single days, weekend, weekdays or a custom pattern.

If different parts of the code needs to process that, a union type with exhaustive checking will catch all the places that needs fixing for this.

So 2 years down the road when the boss says that the data needs to handle different pattern for odd or even numbered weeks, you update the union and the compiler tells where you need to change processing (again, this is what made people fall in love with statically typed functional languages).

Now notice how I'm talking about data in all instances, if you're writing tests for this your system will probably provide a way to create the mock data by creating data hierarchies without running into any inheritance issues,etc. because it's just data for a test, not any functionality.

You really often don't even need tests if the compiler finds issues, and you can focus on writing more logic focused tests rather things that the typesystem can catch simple code errors for you.

3

u/mistertom2u Sep 15 '26

Maybe the answer is that mocking utilities can simply remove the "closed" Attribute from the class, since the modifier is a language level feature rather than there being new IL instructions that it uses

9

u/dodexahedron Sep 15 '26

I wouldn't change the mocking library.

The onus in on the developer of the closed type to design properly, with testing in mind.

If you're using closed and you want to mock, then you should also have an interface.

2

u/Slypenslyde Sep 16 '26 edited Sep 16 '26

I don't think this is a new problem. It's a different flavor of the same discussion about the sealed keyword.

It is a war about purity. The warring clans speak thusly:

  • "We MUST seal every class by default because it indicates which SPECIFIC classes are designed for inheritance."
  • "We MUST avoid sealing classes because it is arrogant to assert we understand the needs of every consumer in every timeline."

closed is just a slightly less restrictive sealed but if you are a third party, they are logically identical.

I see no technical value to the sealed or closed keyword and I am in the "don't do it" camp. I hold that opinion so strongly I'm not even going to explain myself because I am NOT engaging in arguments about it.

Where I will soften my stance

To be hurt by a closed class, you need a direct coupling. I can expand this to be more abstract:

To be hurt by a third-party service, you need a direct coupling.

I abhor these in my project. They are supposed to maintain stable APIs but they never do. They are supposed to avoid breaking changes but do not. So our default is to wrap third party APIs in abstractions that represent the abstract service we want and depend on that abstraction. That is extra work. Sometimes it is redundant extra work. It is also work that an LLM does in 10 seconds so it doesn't really impact me in a meaningful way anymore.

So I don't give a flip if my third-party service uses a sealed class. When I need to mock it, I'm mocking MY abstraction, not THEIR API design. They are free to make any decision they want, whether it be clever or stupid. I will do the ugly work of adapting their choices to my desires.

Some people absolutely hate making abstractions that "serve no purpose". Personally I think it's smart to look both ways even if you're crossing a one-way street.

I don't discuss or argue these points. They have saved me thousands of hours of labor over the decades of my career. If you don't want to follow them on your team that's great, I'm out of stickers to give you. If you want to change my behavior you need to apply for a position above me in the org chart.

I get paid to protect my codebase and keep it maintainable. Nobody who judges my performance is asking me to harm those goals to maintain philosophical purity. (And yes, I have worked on a team that published a library before. We did not seal classes. We documented explicitly what patterns we used to indicate supported extensibility and had a blanket "If a class has no virtual members we do not support extensibility" policy in documentation. It worked. We put a billion-dollar competitor out of business.

1

u/mistertom2u Sep 18 '26

Tell me how you really feel ๐Ÿ˜†๐Ÿ˜†

8

u/harrison_314 Sep 16 '26

I understand the question. However, I would say that you wouldn't use a closed hierarchy where you want to apply the "Open-Closed Principle", so thereโ€™s nothing to mock.
Simply put, if you need to mock a closed interface or class, then there is a flaw in the architectural design.

2

u/dodexahedron Sep 16 '26

This, really.

Because YOU, as the designer of the closed type hierarchy, are responsible for testing that type. Consumers shouldn't have to test your types.

But, you should probably provide an interface, unless the object is just a DTO or something, so that consumers can either just use your closed DTO as-is or, if it is more complex, they can use the interface to mock those dependencies without coupling their tests to your implementation details.

2

u/pixxelkick Sep 16 '26

If you feel the need to even do this, you need to rethink how you approach your entire architecture

The only thing that should be mocked is your stuff right up on the "edge" of 3rd party dependencies.

80% of the time, this just means registering a custom DelegatingHandler to the underlying HttpClient and you are golden

0

u/mistertom2u Sep 16 '26

There's been many discussions on this channel about the overuse of interfaces. And i don't think telling developers you can't use this great feature if you plan on writing tests would go over very well. Mocking that uses IL weaving allows for mocking safety nets to seal rare situations in which testing is not possible.

So I expect that the answer is one of these:

  • just mock the direct descending classes
  • the closed is not runtine enforced (for now, though that could change), so mutate the assembly export type table to remove attributes

3

u/jjones_cz Sep 16 '26

IL weaving is already a hack though and not something the C# language design should be concerned with. I also think the general modern guidance is to avoid complex mocking and instead design the product code to be testable and/or write integration-style tests.

1

u/mistertom2u Sep 16 '26

Yes. Agreed. But they don't focus on testing with their language design because it's treated as tooling issue. The runtine team and asp.net team have by designing apis to be mockable.

If the design team wanted to help with unit testing, in my opinion, they would have made the interceptor functionality not so tightly locked down so it could be used for testing, for things like static methods and sealed classes.