Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save plainionist/13e27a6442f64d5c6517dde7d4668149 to your computer and use it in GitHub Desktop.
Save plainionist/13e27a6442f64d5c6517dde7d4668149 to your computer and use it in GitHub Desktop.
Code analyzer preventing test assemblies from being referenced
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UnitTestAssembliesMustNotBeReferenced : DiagnosticAnalyzer
{
public const string DiagnosticId = "Architecture";
private static DiagnosticDescriptor Descriptor { get; } =
new DiagnosticDescriptor("AR0001",
"UnitTest assemblies must not be referenced by other assemblies",
"The assembly '{0}' references the unit test assembly: {1}",
category: "Architecture",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Descriptor);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationAction(AnalyzeCompilation);
}
private void AnalyzeCompilation(CompilationAnalysisContext context)
{
foreach (var item in context.Compilation.References)
{
if (Path.GetFileNameWithoutExtension(item.Display)
.EndsWith(".UnitTests", StringComparison.OrdinalIgnoreCase))
{
context.ReportDiagnostic(
Diagnostic.Create(
Descriptor,
null,
context.Compilation.AssemblyName,
Path.GetFileNameWithoutExtension(item.Display)));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment