using System.Collections.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Testing.Model; using Shouldly; namespace Roslyn.Testing.CodeFix; public abstract class CSharpCodeFixProviderTest : FileReaderTest where TDiagnosticAnalyzer : DiagnosticAnalyzer, new() where TCodeFixProvider : CodeFixProvider, new() { #region To be implemented by Test classes /// public override string Filepath => _codeFixProvider.GetType() .Name; /// public override string PathToTestData => "./TestData/CodeFix/"; protected virtual IReadOnlyCollection GetAdditionalReferences() => []; #endregion private readonly TCodeFixProvider _codeFixProvider = new(); private readonly TDiagnosticAnalyzer _diagnosticAnalyzer = new(); /// /// Called to test a C# codefix when applied on the inputted string as a source /// /// /// A class in the form of a string before the CodeFix was /// applied to it /// /// /// A class in the form of a string after the CodeFix was /// applied to it /// /// /// Index determining which codefix to apply if there /// are multiple /// /// /// A bool controlling whether or not the test will fail if the CodeFix introduces /// other warnings after being applied /// protected void VerifyFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) { var result = _codeFixProvider.VerifyFix(LanguageNames.CSharp, _diagnosticAnalyzer, oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics, GetAdditionalReferences()); if (result.Success) { return; } if (string.IsNullOrEmpty(result.ErrorMessage)) { result.NewSource.ShouldContainWithoutWhitespace(result.ActualSource); } else { result.Success.ShouldBeTrue(result.ErrorMessage); } } }