Current Scenario:
 Similar to Sealed class peanut butter, I would like to declare class as sealed. There are many cases where class needs to be unsea

[Proposal]: Make unit testing in C# simpler for mocking classes without making members virtual #6251

submited by
Style Pass
2022-06-30 02:30:09

Current Scenario: Similar to Sealed class peanut butter, I would like to declare class as sealed. There are many cases where class needs to be unsealed so that it can be mocked and requires method be declared virtual or be extracted to interface even if there is no need of public interface contracts to be shared e.g. in ASP.NET Core API where Swagger doc is shared . This is only done for unit / application testing - which seems quite odd as just for testing we are opening class which otherwise shouldn't be be case. It also breaks encapsulation and may or may not affect performance as well.

Currently, the mocking classes usually services that makes network call (like to database or other API) requires the method to be declared as virtual. Most of current mocking libraries are based on Castle Dynamic Proxy or similar. The general idea is it proxies either implements interface or derives from class and intercept the invocations and direct to mock code. However, this overriding behavior is only possible if the method is declared as virtual (either member declared directly as virtual in class or with implementing the interface).

One way can be following - Though InternalsVisibleTo attribute applied using Manifest, the similar attribute may be defined for this. In that case the extra step can be added to generate IL with transformation - as if all members are declared as virtual and class as without sealed keyword and embedding the result assembly in test project instead of actual assembly which is generated without any transformation. The test project should ignore referenced actual assembly. This is just thought, there must be better / elegant to address this.

Leave a Comment