dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
18.71k stars 3.98k forks source link

Avoid directly constructing MEF parts in tests #42814

Open sharwell opened 4 years ago

sharwell commented 4 years ago

This issue tracks MEF exports that suppress RS0033 (Importing constructor should be [Obsolete]) for cases where the part is directly constructed in test code.

Evangelink commented 4 years ago

@sharwell What's the recommended way to avoid the direct construction in tests?

CyrusNajmabadi commented 4 years ago

Hey an appropriate mef container and request the type from it.

Evangelink commented 4 years ago

@CyrusNajmabadi I am not sure to get what you just explained, any example?

CyrusNajmabadi commented 4 years ago

Sure. in lots of tests you'll have something more like:

https://github.com/dotnet/roslyn/blob/29542b0a669071b34fc84fe679c767409460b34f/src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs#L114

Here, instead of instantiating this type directly, we retrieve it using mef from the mef container we have for tests to use.

sharwell commented 4 years ago

Here, instead of instantiating this type directly, we retrieve it using mef from the mef container we have for tests to use.

👍 Yep! This ensures that all test code operating on ICodeActionEditHandlerService (from this example) is operating on the same instance of ICodeActionEditHandlerService, which is the same behavior the application has at runtime. The analyzers related to MEF construction provide a much stronger relation between test behavior and production code behavior.